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

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

相关推荐
日升2 分钟前
Browser-use:基于 Python 的智能浏览器自动化 AI 工具调研与实战
人工智能·python·openai
老哥不老4 分钟前
从零掌握 Playwright:用 Python 玩转现代浏览器自动化
开发语言·python·自动化
yngsqq14 分钟前
批量改CAD图层颜色——CAD c#二次开发
开发语言·数据库·c#
码界筑梦坊17 分钟前
基于大数据的美团外卖数据可视化分析系统
大数据·python·信息可视化
Hello.Reader18 分钟前
迭代器介绍与使用(四十一)
开发语言·c++
储悠然29 分钟前
Lisp语言的物联网数据分析
开发语言·后端·golang
东方珵蕴1 小时前
COBOL语言的折线图
开发语言·后端·golang
知识中的海王1 小时前
js逆向入门图灵爬虫练习平台 第四题学习
开发语言·前端·javascript
光算科技1 小时前
无限滚动(Infinite Scroll)页面谷歌不收录!必须改回分页吗?
java·开发语言
重生之我要成为代码大佬1 小时前
从零讲透DFS-深度优先搜索-2(排序与组合)
开发语言·python·算法·深度优先遍历