3分钟Python文件处理方法
Python 的多功能性和易用性使其成为处理各种任务(包括文件操作)的热门选择。无论是从文件中读取数据、写入数据还是操作其内容,Python 都提供了强大的工具和库来简化流程。 Python 中的文件处理涉及执行读取和写入磁盘上存储的文件等操作。Python 提供了内置的函数和方法来促进这些操作,使处理不同格式和大小的文件变得简单。
读取文件的访问模式
在 Python 中处理文件的关键函数是 open() 函数。
open() 函数接受两个参数;filename 和 mode。有四种不同的打开文件的方法(模式):“r” — 读取 — 默认值。打开文件进行读取,如果文件不存在,则出错“a” — Append — 打开要追加的文件,如果文件不存在,则创建该文件“w” — Write — 打开文件进行写入,如果文件不存在,则创建该文件“x” — 创建 — 创建指定的文件,如果文件存在,则返回错误
语法:
f = open("demofile.txt")
打开和关闭文件
文件处理的第一步是打开文件进行读取和/或写入。Python 的 open() 函数用于打开文件,指定文件名和模式(“r”用于读取,“w”用于写入,“a”用于追加等)。完成后,必须使用 close() 方法关闭文件以释放系统资源。
python代码:
# Open a file for reading
file = open('example.txt', 'r')
# Read data from the file
data = file.read()
# Close the file
file.close()
从文件中读取
Python 提供了多种从文件中读取数据的方法,例如 read()、readline() 和 readlines()。这些方法允许您分别读取整个文件(一次一行)或将所有行读取到列表中。
read() 用于返回整个文件内容,它接受可选的 size 参数,该参数提及要从文件中读取的字节。read() 用于返回整个文件内容,它接受可选的 size 参数,该参数提及要从文件中读取的字节。创建文件句柄后,可以使用单独的步骤从中读取数据。基本上,
- read()
- readline()
- readlines()
read() 将整个文件作为字符串一次读取。
readline() 只读取特定数据行(默认读取第一行)readlines() 读取所有行并返回一个字符串列表,其中每个字符串都是一行数据
# Read the entire file
file = open('example.txt', 'r')
data = file.read()
file.close()
使用该 readline() 方法,我们可以逐行读取文件。默认情况下,此方法读取文件中的第一行。
# Read one line at a time
file = open('example.txt', 'r')
line = file.readline()
file.close()
虽然已经了解了如何使用该 readline() 方法提取整个文件内容,但可以使用该 readlines() 方法实现相同的目的。此方法逐行将文件读取到列表中。
# Read all lines into a list
file = open('example.txt', 'r')
lines = file.readlines()
file.close()
写入文件
要将数据写入文件,请以写入 ('w') 或追加 ('a') 模式打开它,然后使用 write() 方法将数据写入文件。还可以使用 writelines() 方法将行列表写入文件。
python代码:
# Write data to a file
file = open('output.txt', 'w')
file.write('Hello, World!')
file.close()
# Append data to a file
file = open('output.txt', 'a')
file.write('\nThis is a new line.')
file.close()
处理文件错误
在处理文件时处理潜在错误至关重要。Python 的 try-except 块可用于捕获和处理文件操作期间可能发生的异常。
python代码:
try:
file = open('nonexistent_file.txt', 'r')
data = file.read()
file.close()
except FileNotFoundError:
print("File not found!")