Python文件操作笔记

Python文件操作笔记

📚 目录

  1. 文件操作基础
  2. 文件读取操作
  3. 文件写入操作
  4. 文件夹操作
  5. 路径操作
  6. 文件复制和移动
  7. 实用技巧
  8. 常见错误和注意事项
  9. 练习示例

文件操作基础

1.1 打开文件的基本语法

python 复制代码
# 基本语法
file = open('filename.txt', 'mode')
# 操作文件
file.close()

# 推荐使用with语句(自动关闭文件)
with open('filename.txt', 'mode') as file:
    # 文件操作
    pass

1.2 文件打开模式

模式 说明 示例
'r' 只读模式(默认) open('file.txt', 'r')
'w' 写入模式(覆盖原文件) open('file.txt', 'w')
'a' 追加模式 open('file.txt', 'a')
'x' 独占创建模式 open('file.txt', 'x')
'b' 二进制模式 open('file.txt', 'rb')
't' 文本模式(默认) open('file.txt', 'rt')

1.3 编码设置

python 复制代码
# 指定编码格式(推荐)
with open('file.txt', 'r', encoding='utf-8') as file:
    content = file.read()

# 常见编码格式
# utf-8: 支持中文和特殊字符
# gbk: 中文编码
# ascii: 英文编码

文件读取操作

2.1 读取整个文件

python 复制代码
# 读取整个文件内容
with open('file.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

2.2 逐行读取

python 复制代码
# 方法1:使用for循环
with open('file.txt', 'r', encoding='utf-8') as file:
    for line in file:
        print(line.strip())  # strip()去除行末换行符

# 方法2:使用readlines()
with open('file.txt', 'r', encoding='utf-8') as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())

2.3 读取指定字节数

python 复制代码
# 读取前100个字符
with open('file.txt', 'r', encoding='utf-8') as file:
    content = file.read(100)
    print(content)

2.4 读取JSON文件

python 复制代码
import json

# 读取JSON文件
with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
    print(data['name'])
    print(data['age'])

文件写入操作

3.1 写入文本

python 复制代码
# 写入文本(会覆盖原文件)
with open('output.txt', 'w', encoding='utf-8') as file:
    file.write('Hello, World!\n')
    file.write('这是第二行\n')
    file.write('这是第三行\n')

3.2 追加内容

python 复制代码
# 追加内容到文件末尾
with open('output.txt', 'a', encoding='utf-8') as file:
    file.write('这是追加的内容\n')
    file.write('追加模式不会覆盖原文件\n')

3.3 写入多行

python 复制代码
# 写入多行内容
lines = ['第一行\n', '第二行\n', '第三行\n']
with open('output.txt', 'w', encoding='utf-8') as file:
    file.writelines(lines)

3.4 写入JSON文件

python 复制代码
import json

data = {
    'name': '张三',
    'age': 25,
    'city': '北京',
    'hobbies': ['读书', '游泳', '编程']
}

with open('data.json', 'w', encoding='utf-8') as file:
    json.dump(data, file, ensure_ascii=False, indent=2)

文件夹操作

4.1 创建文件夹

python 复制代码
import os

# 创建单个文件夹
os.mkdir('new_folder')

# 创建多层文件夹
os.makedirs('parent/child/grandchild', exist_ok=True)
# exist_ok=True: 如果文件夹已存在,不会报错

4.2 删除文件夹

python 复制代码
import os
import shutil

# 删除空文件夹
os.rmdir('empty_folder')

# 删除文件夹及其内容
shutil.rmtree('folder_to_delete')

4.3 列出文件夹内容

python 复制代码
import os

# 列出当前目录内容
print(os.listdir('.'))

# 列出指定目录内容
print(os.listdir('/path/to/directory'))

# 区分文件和文件夹
for item in os.listdir('.'):
    if os.path.isfile(item):
        print(f"文件: {item}")
    elif os.path.isdir(item):
        print(f"文件夹: {item}")

4.4 遍历文件夹

python 复制代码
import os

# 遍历文件夹及其子文件夹
for root, dirs, files in os.walk('.'):
    print(f'当前目录: {root}')
    print(f'子目录: {dirs}')
    print(f'文件: {files}')
    print('-' * 30)

路径操作

5.1 路径拼接

python 复制代码
import os

# 路径拼接(跨平台兼容)
path = os.path.join('folder', 'subfolder', 'file.txt')
print(path)  # Windows: folder\subfolder\file.txt
             # Linux/Mac: folder/subfolder/file.txt

5.2 路径信息获取

python 复制代码
import os

file_path = '/path/to/file.txt'

# 获取文件名
filename = os.path.basename(file_path)
print(filename)  # file.txt

# 获取目录名
dirname = os.path.dirname(file_path)
print(dirname)  # /path/to

# 获取文件扩展名
extension = os.path.splitext(file_path)[1]
print(extension)  # .txt

# 检查文件是否存在
exists = os.path.exists(file_path)
print(exists)  # True/False

5.3 使用pathlib(现代Python推荐)

python 复制代码
from pathlib import Path

# 创建路径对象
file_path = Path('folder/subfolder/file.txt')

# 路径信息
print(f"文件路径: {file_path}")
print(f"文件名: {file_path.name}")
print(f"文件扩展名: {file_path.suffix}")
print(f"父目录: {file_path.parent}")
print(f"是否存在: {file_path.exists()}")
print(f"文件大小: {file_path.stat().st_size} 字节")

# 路径拼接
new_path = Path('folder') / 'subfolder' / 'file.txt'

文件复制和移动

6.1 复制文件

python 复制代码
import shutil

# 复制文件
shutil.copy('source.txt', 'destination.txt')

# 复制文件夹
shutil.copytree('source_folder', 'destination_folder')

6.2 移动文件

python 复制代码
import shutil

# 移动文件或文件夹
shutil.move('old_location.txt', 'new_location.txt')

6.3 重命名文件

python 复制代码
import os

# 重命名文件
os.rename('old_name.txt', 'new_name.txt')

实用技巧

7.1 文件备份

python 复制代码
import shutil
from datetime import datetime

# 创建带时间戳的备份
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
backup_name = f'file_backup_{timestamp}.txt'
shutil.copy('original.txt', backup_name)

7.2 批量处理文件

python 复制代码
import os

# 批量重命名文件
folder = 'images'
for filename in os.listdir(folder):
    if filename.endswith('.jpg'):
        new_name = f'photo_{filename}'
        os.rename(os.path.join(folder, filename), 
                 os.path.join(folder, new_name))

7.3 文件监控

python 复制代码
import os
import time

# 监控文件变化
def monitor_file(file_path):
    last_modified = os.path.getmtime(file_path)
    while True:
        current_modified = os.path.getmtime(file_path)
        if current_modified != last_modified:
            print(f"文件 {file_path} 已被修改")
            last_modified = current_modified
        time.sleep(1)

常见错误和注意事项

8.1 常见错误

python 复制代码
# ❌ 错误:忘记关闭文件
file = open('test.txt', 'r')
content = file.read()
# 忘记 file.close()

# ✅ 正确:使用with语句
with open('test.txt', 'r') as file:
    content = file.read()

# ❌ 错误:文件不存在时读取
with open('nonexistent.txt', 'r') as file:
    content = file.read()

# ✅ 正确:检查文件是否存在
if os.path.exists('nonexistent.txt'):
    with open('nonexistent.txt', 'r') as file:
        content = file.read()

8.2 编码问题

python 复制代码
# ❌ 错误:不指定编码可能导致乱码
with open('chinese.txt', 'r') as file:
    content = file.read()

# ✅ 正确:指定编码
with open('chinese.txt', 'r', encoding='utf-8') as file:
    content = file.read()

8.3 权限问题

python 复制代码
# 检查文件权限
import os

if os.access('file.txt', os.R_OK):
    print("文件可读")
if os.access('file.txt', os.W_OK):
    print("文件可写")

练习示例

9.1 简单文件操作练习

python 复制代码
# 练习1:创建学生信息文件
students = [
    {'name': '张三', 'age': 20, 'grade': 85},
    {'name': '李四', 'age': 21, 'grade': 92},
    {'name': '王五', 'age': 19, 'grade': 78}
]

# 写入CSV格式
with open('students.csv', 'w', encoding='utf-8') as file:
    file.write('姓名,年龄,成绩\n')
    for student in students:
        file.write(f"{student['name']},{student['age']},{student['grade']}\n")

# 读取并计算平均分
total_grade = 0
count = 0
with open('students.csv', 'r', encoding='utf-8') as file:
    next(file)  # 跳过标题行
    for line in file:
        name, age, grade = line.strip().split(',')
        total_grade += int(grade)
        count += 1

average_grade = total_grade / count
print(f"平均分: {average_grade}")

9.2 文件夹整理练习

python 复制代码
import os
import shutil

# 练习2:按文件类型整理文件夹
def organize_files(source_dir):
    # 创建分类文件夹
    categories = {
        'images': ['.jpg', '.jpeg', '.png', '.gif'],
        'documents': ['.pdf', '.doc', '.docx', '.txt'],
        'videos': ['.mp4', '.avi', '.mov'],
        'music': ['.mp3', '.wav', '.flac']
    }
    
    for category in categories:
        os.makedirs(os.path.join(source_dir, category), exist_ok=True)
    
    # 移动文件
    for filename in os.listdir(source_dir):
        if os.path.isfile(os.path.join(source_dir, filename)):
            file_ext = os.path.splitext(filename)[1].lower()
            
            for category, extensions in categories.items():
                if file_ext in extensions:
                    src = os.path.join(source_dir, filename)
                    dst = os.path.join(source_dir, category, filename)
                    shutil.move(src, dst)
                    break

# 使用示例
organize_files('downloads')

📝 总结

重要概念回顾

  1. 文件操作三步骤:打开 → 操作 → 关闭
  2. 推荐使用with语句:自动处理文件关闭
  3. 指定编码格式:避免中文乱码问题
  4. 路径操作:使用os.path或pathlib
  5. 错误处理:检查文件是否存在和权限

常用模块

  • os: 操作系统接口,文件和目录操作
  • shutil: 高级文件操作(复制、移动)
  • pathlib: 现代路径操作(Python 3.4+)
  • json: JSON文件读写
  • datetime: 时间相关操作

最佳实践

  1. 总是使用with语句处理文件
  2. 指定正确的编码格式
  3. 检查文件是否存在再操作
  4. 使用pathlib进行路径操作
  5. 适当处理异常情况

🔗 相关资源

声明

该文章为学习过程中的笔记,目的是防止自己忘记,也为了方便随时随地查阅。其中大部分内容收集于互联网。

相关推荐
深圳雨林凯AI10 小时前
图案裂变的“风格归一化“设计思路:主体保得住,画风才拉得齐|雨林凯AI技术笔记
人工智能·笔记
问天_观心10 小时前
大模型微调学习(二)
人工智能·python·深度学习·学习·语言模型·transformer
洋洋不叫杨杨10 小时前
揭秘当下知名的SEO优化渠道,你知道几个?
大数据·python
阿童木写作10 小时前
跨境图片翻译工具推荐:批量处理视频字幕与智能抠图
python·音视频
梦想的颜色10 小时前
OCR 识别原理与 Python 识图全实战:从文字提取到图像内容理解
python·计算机视觉·ocr·图像识别·python 识图
禹凕10 小时前
Dijkstra算法详解与应用
python·算法
别走!万哥爱你11 小时前
Python 中可以用于在已排序的列表中查找特定元素的位置的是什么?
python
冬木家居11 小时前
40㎡客厅变形记,小家住出大自由[特殊字符]
android·经验分享·笔记·智能家居·微信公众平台
摇滚侠11 小时前
《SpringBoot 3:入门与应用实战》第 12 章 JDBC 与事务 数据库初始化机制 阅读笔记 36
数据库·spring boot·笔记
wxwx_bscxy32212 小时前
基于Python新冠疫情可视化分析系统的设计与实现
java·数据库·spring boot·python·微信小程序·sqlite