python---文件操作


Python 提供了丰富的文件操作功能,能够轻松地读取、写入和处理文件。

1. 打开文件

使用 open() 函数打开文件,基本语法:

file = open(filename, mode, encoding)

mode参数

决定打开模式:

基本模式字符

模式字符全称描述
rRead只读模式(默认)。文件必须存在
wWrite只写模式。如果文件存在则清空,不存在则创建
aAppend追加模式。如果文件存在则在末尾追加,不存在则创建
xExclusive独占创建模式。如果文件已存在则失败
bBinary二进制模式
tText文本模式(默认)
+Update读写模式(可读可写)

常用模式组合

模式描述文件指针位置
‘r’ 或 ‘rt’只读文本模式文件开头
‘w’ 或 ‘wt’只写文本模式(清空文件)文件开头
‘a’ 或 ‘at’追加文本模式文件末尾
‘r+’读写文本模式(可读可写)文件开头
‘w+’读写文本模式(清空文件)文件开头
‘a+’读写文本模式(追加)文件末尾

二进制模式

模式描述
‘rb’只读二进制模式
‘wb’只写二进制模式(清空文件)
‘ab’追加二进制模式
‘r+b’ 或 ‘rb+’读写二进制模式
‘w+b’ 或 ‘wb+’读写二进制模式(清空文件)
‘a+b’ 或 ‘ab+’读写二进制模式(追加)

encoding参数

设置文件编码格式的参数,默认GBK编码

2. 读取文件

2.1、读取整个文件

with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

2.2、逐行读取

with open('example.txt', 'r', encoding='utf-8') as file:
    for line in file:
        print(line.strip())  # strip() 移除行末的换行符

2.3、读取所有行到列表

with open('example.txt', 'r', encoding='utf-8') as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())

2.4、读取指定字节数

with open('example.txt', 'r', encoding='utf-8') as file:
    chunk = file.read(100)  # 读取前100个字符
    print(chunk)

3. 写入文件

# 覆盖写入
with open('output.txt', 'w', encoding='utf-8') as file:
    file.write('Hello, World!\n')
    file.write('这是第二行\n')

# 追加写入
with open('output.txt', 'a', encoding='utf-8') as file:
    file.write('这是追加的内容\n')

写入多行

lines = ['第一行\n', '第二行\n', '第三行\n']

with open('output.txt', 'w', encoding='utf-8') as file:
    file.writelines(lines)

4. 文件操作最佳实践

4.1使用 with 语句

# 推荐方式 - 自动处理文件关闭
with open('file.txt', 'r') as file:
    data = file.read()

# 不推荐的方式
file = open('file.txt', 'r')
try:
    data = file.read()
finally:
    file.close()

4.2、处理文件路径

import os

# 构建路径
file_path = os.path.join('folder', 'subfolder', 'file.txt')

# 检查文件是否存在
if os.path.exists(file_path):
    print("文件存在")
else:
    print("文件不存在")

5. 二进制文件操作

# 读取二进制文件
with open('image.jpg', 'rb') as file:
    binary_data = file.read()

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

6. 文件位置操作

文件指针操作:

with open('example.txt', 'r') as file:
    # 获取当前位置
    position = file.tell()
    print(f"当前位置: {position}")
    
    # 读取一些内容
    content = file.read(10)
    
    # 移动到文件开头
    file.seek(0)
    
    # 移动到特定位置
    file.seek(5)  # 移动到第5个字节

7. 异常处理

try:
    with open('nonexistent.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("文件不存在")
except PermissionError:
    print("没有权限访问文件")
except Exception as e:
    print(f"发生错误: {e}")

8. 实用文件操作函数

import os
import shutil

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

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

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

# 移动文件
shutil.move('source.txt', 'new_location/source.txt')

# 获取文件信息
file_stats = os.stat('example.txt')
print(f"文件大小: {file_stats.st_size} 字节")
print(f"最后修改时间: {file_stats.st_mtime}")

9. CSV 文件操作示例

import csv

# 读取 CSV 文件
with open('data.csv', 'r', newline='', encoding='utf-8') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# 写入 CSV 文件
data = [
    ['Name', 'Age', 'City'],
    ['Alice', '25', 'New York'],
    ['Bob', '30', 'London']
]

with open('output.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerows(data)

10. JSON 文件操作

import json

# 写入 JSON 文件
data = {
    "name": "Alice",
    "age": 25,
    "cities": ["New York", "London"]
}

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

# 读取 JSON 文件
with open('data.json', 'r', encoding='utf-8') as file:
    loaded_data = json.load(file)
    print(loaded_data)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值