欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > Python入门(8):文件

Python入门(8):文件

2025/5/15 21:41:16 来源:https://blog.csdn.net/qq_56664222/article/details/146989445  浏览:    关键词:Python入门(8):文件

1. 文件基本概念

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

文件类型

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

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

2. 文件打开与关闭

2.1 open() 函数

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

2.2 文件打开模式

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

3. 文件读取方法

3.1 读取整个文件

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

3.2 逐行读取

# 方法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 写入字符串

# 写入模式(会覆盖原文件)
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 写入多行

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

5. 文件位置操作

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. 二进制文件操作

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

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

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 模块)

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 模块)

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. 文件编码处理

# 指定编码方式(推荐)
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 文件处理

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 文件处理

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. 常见文件操作异常处理

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("操作结束")

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词