引言在Python编程中,文件操作是基础且重要的技能。掌握文件读写,可以帮助我们更好地处理数据、存储信息。本文将详细介绍Python3中文件操作的各个方面,包括打开文件、读取文件、写入文件、关闭文件以...
在Python编程中,文件操作是基础且重要的技能。掌握文件读写,可以帮助我们更好地处理数据、存储信息。本文将详细介绍Python3中文件操作的各个方面,包括打开文件、读取文件、写入文件、关闭文件以及错误处理,旨在帮助读者轻松掌握文本和二进制文件的读写技巧。
在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':文本模式(默认值)。'+':更新模式,既可以读也可以写。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)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!')with open('file.txt', 'a', encoding='utf-8') as file: file.write('Append text.')使用close()方法关闭文件,释放资源。
file.close()或使用with语句自动关闭文件:
with open('file.txt', 'r', encoding='utf-8') as file: content = file.read() print(content)在文件操作过程中,可能会遇到各种错误。使用try-except语句进行错误处理。
try: with open('file.txt', 'r', encoding='utf-8') as file: content = file.read() print(content)
except FileNotFoundError: print('文件不存在!')
except IOError: print('文件操作错误!')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文件操作的各个方面。在实际应用中,灵活运用这些技巧,可以帮助我们更好地处理文件,实现数据存储和交换。