首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[教程]Python3文件读写全攻略:轻松掌握文本、二进制文件操作技巧

发布于 2025-07-20 21:30:07
0
287

引言在Python编程中,文件操作是基础且重要的技能。掌握文件读写,可以帮助我们更好地处理数据、存储信息。本文将详细介绍Python3中文件操作的各个方面,包括打开文件、读取文件、写入文件、关闭文件以...

引言

在Python编程中,文件操作是基础且重要的技能。掌握文件读写,可以帮助我们更好地处理数据、存储信息。本文将详细介绍Python3中文件操作的各个方面,包括打开文件、读取文件、写入文件、关闭文件以及错误处理,旨在帮助读者轻松掌握文本和二进制文件的读写技巧。

1. 打开文件

在Python中,使用open()函数打开文件。该函数的基本语法如下:

file_object = open(filename, mode, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

其中,filename是要打开的文件名,mode是文件打开的模式。

打开模式

  • 'r':只读模式(默认值)。
  • 'w':写入模式,如果文件存在则覆盖,不存在则创建。
  • 'x':排他性创建,如果文件已存在则操作失败。
  • 'a':追加模式,写入到文件末尾。
  • 'b':二进制模式。
  • 't':文本模式(默认值)。
  • '+':更新模式,既可以读也可以写。

2. 读取文件

文本文件读取

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

二进制文件读取

with open('file.bin', 'rb') as file: content = file.read() print(content)

3. 写入文件

文本文件写入

with open('file.txt', 'w', encoding='utf-8') as file: file.write('Hello, World!')

二进制文件写入

with open('file.bin', 'wb') as file: file.write(b'Hello, World!')

4. 追加文件

with open('file.txt', 'a', encoding='utf-8') as file: file.write('Append text.')

5. 关闭文件

使用close()方法关闭文件,释放资源。

file.close()

或使用with语句自动关闭文件:

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

6. 错误处理

在文件操作过程中,可能会遇到各种错误。使用try-except语句进行错误处理。

try: with open('file.txt', 'r', encoding='utf-8') as file: content = file.read() print(content)
except FileNotFoundError: print('文件不存在!')
except IOError: print('文件操作错误!')

7. 文件操作实例

读取多个文件

import os
for filename in os.listdir('.'): if filename.endswith('.txt'): with open(filename, 'r', encoding='utf-8') as file: content = file.read() print(content)

写入多个文件

import os
for filename in os.listdir('.'): if filename.endswith('.txt'): with open(filename, 'w', encoding='utf-8') as file: file.write('Hello, World!')

总结

通过本文的介绍,相信读者已经掌握了Python3文件操作的各个方面。在实际应用中,灵活运用这些技巧,可以帮助我们更好地处理文件,实现数据存储和交换。

评论
一个月内的热帖推荐
csdn大佬
Lv.1普通用户

452398

帖子

22

小组

841

积分

赞助商广告
站长交流