5分钟掌握在Python中处理文件的8种基本操作
I在 Python 中处理文件是一项常见任务,Python 提供了几个内置函数和模块来帮助您读取、写入和操作文件。以下是在 Python 中处理文件时可以执行的一些基本操作:
- 打开文件:您可以使用该函数在 Python 中打开文件。它有两个参数:文件路径和模式(例如,“r”表示读取,“w”表示写入,“a”表示追加等)。open()
# Opening a file for reading
file = open('example.txt', 'r')
# Opening a file for writing
file = open('example.txt', 'w')
# Opening a file for appending
file = open('example.txt', 'a')
2. 从文件中读取:
可以使用 file 对象提供的各种方法读取文件的内容:
- read():以字符串形式读取整个文件内容。
- readline():一次读取一行。
- readlines():读取所有行并将它们作为列表返回。
# Reading the entire file
content = file.read()
# Reading one line at a time
line = file.readline()
# Reading all lines into a list
lines = file.readlines()
3. 写入文件:
若要将数据写入文件,请使用该方法。write()
# Writing data to a file
file.write("Hello, world!")
4. 附加到文件:
若要将数据追加到现有文件的末尾,请使用“a”模式或具有追加模式的方法。write()
# Appending data to a file
file = open('example.txt', 'a')
file.write("Appending text")
5. 关闭文件:
使用完文件后关闭文件以释放系统资源非常重要。
file.close()
或者,可以使用语句,该语句在您完成文件后自动关闭文件:with
with open('example.txt', 'r') as file:
content = file.read()
# File is automatically closed when the block exits.
6. 遍历行:
可以使用循环遍历文件的行。for
with open('example.txt', 'r') as file:
for line in file:
print(line)
7.文件模式:
- 'r':读取(默认)。
- 'w':写入(创建新文件或截断现有文件)。
- 'a':追加(创建新文件或追加到现有文件)。
- 'b':二进制模式(例如,用于读取二进制文件)。'rb'
- 't':文本模式(默认)。
8. 文件处理错误:
在处理文件时,尤其是在打开和读取/写入文件时,请始终处理异常。
try:
with open('example.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found.")
except IOError:
print("An error occurred while reading the file.")