Python有許多處理文本文件的庫,以下是其中一些常用的庫:
# 打開文件并讀取內容
file = open('filename.txt', 'r')
content = file.read()
file.close()
# 打開文件并寫入內容
file = open('filename.txt', 'w')
file.write('Hello, World!')
file.close()
import os
# 讀取文件內容
content = os.popen('cat filename.txt').read()
# 寫入文件內容
os.popen('echo "Hello, World!" > filename.txt')
import io
# 打開文件并讀取內容
with io.open('filename.txt', 'r', encoding='utf-8') as file:
content = file.read()
# 打開文件并寫入內容
with io.open('filename.txt', 'w', encoding='utf-8') as file:
file.write('Hello, World!')
import csv
# 讀取CSV文件內容
with open('filename.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
# 寫入CSV文件內容
with open('filename.csv', 'w') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age'])
writer.writerow(['John', '25'])
import pandas as pd
# 讀取CSV文件內容
df = pd.read_csv('filename.csv')
# 寫入CSV文件內容
df.to_csv('filename.csv', index=False)
這只是一些常用的庫,如果你有特定的需求,還可以根據情況選擇其他適合的庫。