一、读取txt文件
1.1 读取文件内容:
# 打开文件并读取内容
with open('example.txt', 'r') as file:
content = file.read()
print(content)
1.2 逐行读取文件内容:
# 逐行读取文件内容
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # 去除每行末尾的换行符
1.3 写入文件内容:
# 写入文件内容
with open('output.txt', 'w') as file:
file.write("Hello, world!\n")
file.write("This is a sample file.\n")
1.4 追加内容到文件:
# 追加内容到文件
with open('output.txt', 'a') as file:
file.write("This line is appended.\n")
二、处理csv文件
2.1 读取csv文件
import csv
# 读取 CSV 文件
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
2.2 写入 CSV 文件
import csv
# 写入 CSV 文件
data = [
['Name', 'Age'],
['Alice', 30],
['Bob', 25],
['Charlie', 35]
]
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
三、使用 pathlib
模块操作文件路径:
from pathlib import Path
# 检查文件是否存在
file_path = Path('example.txt')
if file_path.exists():
print("File exists")
# 获取文件的绝对路径
print("Absolute path:", file_path.absolute())
# 获取文件的父目录
print("Parent directory:", file_path.parent)