欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > Python文件操作完全指南

Python文件操作完全指南

2025/11/12 22:24:00 来源:https://blog.csdn.net/shangjg03/article/details/148212933  浏览:    关键词:Python文件操作完全指南

1.文件操作基础

在Python中,文件操作是日常编程中经常会遇到的需求,包括读取配置文件、写入日志、处理数据文件等。Python提供了内置的`open()`函数来打开文件,并通过不同的模式来控制文件的读写行为。

1. 打开文件

# 打开文件,使用with语句会自动关闭文件
with open('example.txt', 'r') as file:
    content = file.read()print(content)

2. 文件打开模式

模式

描述

'r'

读取模式(默认)

'w'

写入模式,会覆盖已有文件

'a'

追加模式,在文件末尾添加内容

'x'

创建模式,如果文件存在则报错

'b'

二进制模式

't'

文本模式(默认)

2.文件读取操作

1. 读取整个文件内容

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

2. 逐行读取文件

with open('example.txt', 'r') as file:for line in file:print(line.strip())  # 去除行末的换行符

3. 读取指定数量的字符/字节

with open('example.txt', 'r') as file:
    first_10_chars = file.read(10)  # 读取前10个字符
    next_5_chars = file.read(5)     # 从第11个字符开始读取5个字符print(f"前10个字符: {first_10_chars}")print(f"接下来的5个字符: {next_5_chars}")

3.文件写入操作

1. 写入文本内容

with open('output.txt', 'w') as file:file.write("Hello, World!\n")file.write("This is a test.\n")

2. 追加内容到文件

with open('output.txt', 'a') as file:file.write("Appended line.\n")

3. 写入多行内容

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('output.txt', 'w') as file:file.writelines(lines)

4.文件和目录操作

除了基本的文件读写,Python还提供了强大的文件和目录管理功能,主要通过`os`和`os.path`模块实现。

1. 检查文件是否存在

import osif os.path.exists('example.txt'):print("文件存在")
else:print("文件不存在")

2. 重命名和删除文件

import os# 重命名文件
os.rename('old_name.txt', 'new_name.txt')# 删除文件
if os.path.exists('temp.txt'):
    os.remove('temp.txt')

3. 创建和删除目录

import os# 创建目录
os.mkdir('new_directory')# 删除目录(必须为空)
os.rmdir('new_directory')# 创建多级目录
os.makedirs('level1/level2/level3')# 删除多级目录
import shutil
shutil.rmtree('level1')  # 会删除整个目录树

4. 遍历目录

import os# 遍历当前目录下的所有文件和子目录
for entry in os.scandir('.'):
    if entry.is_file():
        print(f"文件: {entry.name}")
    elif entry.is_dir():
        print(f"目录: {entry.name}")# 递归遍历目录树
for root, dirs, files in os.walk('.'):
    print(f"目录: {root}")
    for file in files:
        print(f"  文件: {file}")

5.高级文件操作

1. 使用上下文管理器自定义文件操作

class FileHandler:def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = Nonedef __enter__(self):
        self.file = open(self.filename, self.mode)return self.filedef __exit__(self, exc_type, exc_value, traceback):if self.file:
            self.file.close()# 使用自定义上下文管理器
with FileHandler('custom.txt', 'w') as file:file.write("Custom context manager example.\n")

2. 文件复制和移动

import shutil# 复制文件
shutil.copy('source.txt', 'destination.txt')# 移动文件
shutil.move('source.txt', 'new_location/')

3. 读取和写入JSON文件

import json# 写入JSON数据
data = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('data.json', 'w') as file:
    json.dump(data, file, indent=4)# 读取JSON数据
with open('data.json', 'r') as file:
    loaded_data = json.load(file)
    print(loaded_data)

6.异常处理

在进行文件操作时,可能会遇到各种异常情况,如文件不存在、权限不足等,因此需要进行适当的异常处理。

try:with open('nonexistent.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:print("错误:文件不存在")
except PermissionError:print("错误:没有访问权限")
except Exception as e:print(f"错误:发生了未知错误 - {e}")
else:print("文件读取成功")
finally:print("文件操作完成")

7.总结

Python提供了丰富而灵活的文件操作功能,无论是简单的文本文件处理,还是复杂的目录结构管理,都能轻松应对。掌握这些文件操作技术,将大大提高你处理数据和配置的效率。建议在实际应用中,根据具体需求选择合适的文件操作方式,并始终记得进行异常处理,确保程序的健壮性。

版权声明:

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

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

热搜词