目录

第十八章:文件操作

本章目标

完成本章学习后,你将能够:

文件读写基础

打开文件

# 基本语法
f = open('file.txt', 'r', encoding='utf-8')
content = f.read()
f.close()
 
# 使用with语句(推荐)
with open('file.txt', 'r', encoding='utf-8') as f:
    content = f.read()
# 自动关闭文件

读取模式

# 读取整个文件
with open('file.txt', 'r', encoding='utf-8') as f:
    content = f.read()  # 返回字符串
 
# 按行读取
with open('file.txt', 'r', encoding='utf-8') as f:
    for line in f:
        print(line.strip())
 
# 读取为列表
with open('file.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()
 
# 逐行读取(大文件)
with open('file.txt', 'r', encoding='utf-8') as f:
    while True:
        line = f.readline()
        if not line:
            break
        print(line.strip())

写入模式

# 写入(覆盖)
with open('output.txt', 'w', encoding='utf-8') as f:
    f.write('Hello, World!\n')
    f.write('Second line\n')
 
# 追加
with open('log.txt', 'a', encoding='utf-8') as f:
    f.write('New log entry\n')
 
# 写入多行
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('output.txt', 'w', encoding='utf-8') as f:
    f.writelines(lines)

文件系统操作

import os
import shutil
 
# 路径操作
print(os.path.join('folder', 'file.txt'))  # folder/file.txt
print(os.path.abspath('file.txt'))
print(os.path.dirname('/path/to/file.txt'))
print(os.path.basename('/path/to/file.txt'))
print(os.path.splitext('file.txt'))  # ('file', '.txt')
 
# 文件/目录操作
os.mkdir('new_folder')           # 创建目录
os.makedirs('a/b/c', exist_ok=True)  # 递归创建
os.remove('file.txt')            # 删除文件
os.rmdir('empty_folder')         # 删除空目录
shutil.rmtree('folder')          # 删除目录及内容
shutil.copy('src.txt', 'dst.txt')    # 复制文件
shutil.move('src.txt', 'dst/')       # 移动文件
 
# 遍历目录
for root, dirs, files in os.walk('.'):
    for file in files:
        print(os.path.join(root, file))

处理不同文件格式

JSON

import json
 
data = {'name': 'Alice', 'age': 25, 'hobbies': ['reading', 'coding']}
 
# 写入JSON
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=2, ensure_ascii=False)
 
# 读取JSON
with open('data.json', 'r', encoding='utf-8') as f:
    loaded_data = json.load(f)
 
# 字符串转换
json_str = json.dumps(data, indent=2)
parsed = json.loads(json_str)

CSV

import csv
 
# 写入CSV
with open('data.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerow(['Name', 'Age', 'City'])
    writer.writerow(['Alice', 25, 'NYC'])
    writer.writerow(['Bob', 30, 'LA'])
 
# 读取CSV
with open('data.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
 
# 字典方式
with open('data.csv', 'r', encoding='utf-8') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row['Name'], row['Age'])

本章练习

1. 实现文件复制工具 2. 实现日志文件分析器 3. 实现目录同步工具 4. 实现配置文件管理器

下一章:第十九章:异常处理