Write Excel with Pandas

สร้าง pandas DataFrame

%python
import pandas as pd
import openpyxl

df = pd.DataFrame([[11, 21, 31], [12, 22, 32], [31, 32, 33]],
                  index=['one', 'two', 'three'], columns=['a', 'b', 'c'])

print(df)

#         a   b   c
# one    11  21  31
# two    12  22  32
# three  31  32  33

print(type(df))
# <class 'pandas.core.frame.DataFrame'>

เขียน pandas DataFrame ลงไฟล์

%python
path = '/tmp/'
filename = f'{path}output1.xlsx'
print(filename)
with pd.ExcelWriter(filename) as writer:  
     df.to_excel(writer, sheet_name='Sheet_name_1')

Python subprocess

subprocess.call() – เก่าแล้ว Older high-level API

ใช้ subprocess.check_call() , subprocess.run() แทน

ตัวอย่าง 1

echo คำว่า test1 test2 ลงไปที่ไฟล์ /tmp/out.txt

%python
import subprocess
e = 'echo "test1 test2" > /tmp/out.txt'
subprocess.call(e, shell=True)

ตัวอย่าง 2

ตั้งชื่อไฟล์ของ log เป็นวันเวลาปัจจุบัน ไว้ใต้ /tmp แล้วใส่ข้อความ Hello World! ลงไป ด้วยการ echo

%python
import datetime
import subprocess
 
run_time = datetime.datetime.now() + datetime.timedelta(hours=7)
tmp_file = '/tmp/' + run_time.strftime("%Y-%m-%dT%H:%M:%S") + '.log'
print(tmp_file) # /tmp/2023-02-21T13:23:52.log

e = f'echo "Hello World!" >> {tmp_file}'
subprocess.call(e, shell=True)

ตรวจสอบว่าได้สร้างไฟล์ขึ้นมามั๊ย

%sh ls -l '/tmp/'

ดูเนื้อหาในไฟล์

%sh cat '/tmp/2023-02-21T13:23:52.log'

ใช้ Pandas อ่าน Text file

%python
import pandas as pd

# read text file
df = pd.read_fwf('/tmp/2023-02-21T14:55:00.log')
print(type(df))
print(df)
print(df.count())