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)
这只是一些常用的库,如果你有特定的需求,还可以根据情况选择其他适合的库。