Python入门(8):文件

1. 文件基本概念

文件:存储在计算机上的数据集合,Python 通过文件对象来操作文件。

文件类型

  • 文本文件:由字符组成,如 .txt, .py

  • 二进制文件:由字节组成,如 .jpg, .mp3

2. 文件打开与关闭

2.1 open() 函数

python 复制代码
# 打开文件的基本语法
file = open('example.txt', 'r')  # 'r'表示读取模式
file.close()  # 关闭文件

2.2 文件打开模式

模式 描述
'r' 只读(默认)
'w' 写入(会覆盖)
'a' 追加
'x' 创建新文件
'b' 二进制模式
't' 文本模式(默认)
'+' 读写模式
python 复制代码
# 使用 with 语句自动管理文件(推荐)
with open('example.txt', 'r') as file:
    content = file.read()  # 读取文件内容
# 离开 with 块后文件自动关闭

3. 文件读取方法

3.1 读取整个文件

python 复制代码
with open('example.txt', 'r') as file:
    content = file.read()  # 读取全部内容为字符串
    print(content)

3.2 逐行读取

python 复制代码
# 方法1:使用 readline()
with open('example.txt', 'r') as file:
    line = file.readline()  # 读取一行
    while line:
        print(line.strip())  # strip() 去除换行符
        line = file.readline()

# 方法2:使用 readlines()
with open('example.txt', 'r') as file:
    lines = file.readlines()  # 读取所有行到列表
    for line in lines:
        print(line.strip())

# 方法3:直接迭代文件对象(推荐)
with open('example.txt', 'r') as file:
    for line in file:  # 逐行迭代
        print(line.strip())

4. 文件写入方法

4.1 写入字符串

python 复制代码
# 写入模式(会覆盖原文件)
with open('output.txt', 'w') as file:
    file.write("Hello, World!\n")  # 写入字符串
    file.write("This is a new line.\n")

# 追加模式
with open('output.txt', 'a') as file:
    file.write("This line will be appended.\n")

4.2 写入多行

python 复制代码
lines = ["First line\n", "Second line\n", "Third line\n"]
with open('output.txt', 'w') as file:
    file.writelines(lines)  # 写入多行

5. 文件位置操作

python 复制代码
with open('example.txt', 'rb') as file:  # 二进制模式才能使用 seek()
    print(file.tell())  # 获取当前文件位置(字节偏移量)
    content = file.read(10)  # 读取10个字节
    print(content)
    file.seek(5)  # 移动到第5个字节
    print(file.read(5))  # 读取接下来的5个字节

6. 二进制文件操作

python 复制代码
# 读取二进制文件
with open('image.jpg', 'rb') as file:
    data = file.read()  # 读取二进制数据

# 写入二进制文件
with open('copy.jpg', 'wb') as file:
    file.write(data)  # 写入二进制数据

7. 文件与目录操作(os 模块)

python 复制代码
import os

# 检查文件/目录是否存在
print(os.path.exists('example.txt'))  # True/False

# 获取文件大小
print(os.path.getsize('example.txt'))  # 字节数

# 重命名文件
os.rename('old.txt', 'new.txt')

# 删除文件
os.remove('file_to_delete.txt')

# 目录操作
os.mkdir('new_dir')  # 创建目录
os.rmdir('empty_dir')  # 删除空目录

8. 文件路径操作(os.path 模块)

python 复制代码
import os.path

# 获取绝对路径
print(os.path.abspath('example.txt'))

# 检查是否为文件/目录
print(os.path.isfile('example.txt'))  # True
print(os.path.isdir('example.txt'))  # False

# 路径拼接
print(os.path.join('folder', 'subfolder', 'file.txt'))

# 获取文件名和扩展名
print(os.path.basename('/path/to/file.txt'))  # 'file.txt'
print(os.path.splitext('file.txt'))  # ('file', '.txt')

9. 临时文件(tempfile 模块)

python 复制代码
import tempfile

# 创建临时文件
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
    temp_file.write(b"Temporary data")  # 写入临时数据
    temp_path = temp_file.name  # 获取临时文件路径
    print(f"临时文件路径: {temp_path}")

# 临时文件会在关闭后自动删除(除非设置 delete=False)

10. 文件编码处理

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

# 处理编码错误
try:
    with open('example.txt', 'r', encoding='utf-8') as file:
        content = file.read()
except UnicodeDecodeError:
    print("文件编码不匹配!")

# 写入时指定编码
with open('output.txt', 'w', encoding='utf-8') as file:
    file.write("包含中文的内容")

11. CSV 文件处理

python 复制代码
import csv

# 读取CSV文件
with open('data.csv', 'r', encoding='utf-8') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)  # 每行是一个列表

# 写入CSV文件
data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
with open('output.csv', 'w', encoding='utf-8', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)  # 写入多行

12. JSON 文件处理

python 复制代码
import json

# 写入JSON文件
data = {'name': 'Alice', 'age': 25, 'skills': ['Python', 'Java']}
with open('data.json', 'w', encoding='utf-8') as file:
    json.dump(data, file, indent=4)  # indent参数美化输出

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

13. 文件操作最佳实践

  1. 始终使用 with 语句管理文件资源

  2. 明确指定文件编码(特别是处理文本时)

  3. 处理大文件时使用迭代方式而非一次性读取

  4. 检查文件/目录是否存在再进行操作

  5. 合理处理文件操作可能引发的异常

  6. 使用 os.path 进行路径操作而非字符串拼接

  7. 敏感操作前对数据做好备份

14. 常见文件操作异常处理

python 复制代码
try:
    with open('nonexistent.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("文件不存在!")
except PermissionError:
    print("没有文件访问权限!")
except IOError as e:
    print(f"文件操作错误: {e}")
finally:
    print("操作结束")

如果您觉得本文章对您有帮助,别忘了点赞、收藏加关注,更多干货内容将持续发布,您的支持就是作者更新最大的动力。本专栏将持续更新,有任何问题都可以在评论区讨论

相关推荐
工藤新一¹16 分钟前
C++/SDL 进阶游戏开发 —— 双人塔防(代号:村庄保卫战 14)
开发语言·c++·游戏引擎·游戏开发·sdl·实践项目
一个天蝎座 白勺 程序猿23 分钟前
Python爬虫(8)Python数据存储实战:JSON文件读写与复杂结构化数据处理指南
爬虫·python·json
钢铁男儿24 分钟前
C#核心技术解析:静态类型、dynamic与可空类型
开发语言·c#
q_q王39 分钟前
dify对接飞书云文档,并且将图片传入飞书文档
python·大模型·飞书·dify·智能体·图片展示
noravinsc1 小时前
django filter 排除字段
后端·python·django
卓越进步1 小时前
层级时间轮的 Golang 实现原理与实践
开发语言·后端·golang
zandy10111 小时前
嵌入式BI开发指南:如何通过衡石API将分析能力集成到业务系统?
开发语言·python·嵌入式
沉迷...1 小时前
el-input限制输入只能是数字 限制input只能输入数字
开发语言·前端·elementui
<但凡.1 小时前
C++修炼:list模拟实现
开发语言·数据结构·c++
曲幽1 小时前
零基础快速搭建AI绘画网站!用Gradio玩转Stable Diffusion
python·ai作画·stable diffusion·gradio·diffusers·webui