7.Python文件操作:文件的打开与关闭、文件的读写、文件读写应用
1. 文件的打开与关闭
打开文件
在 Python 中,使用 open()
函数来打开文件。open()
返回一个文件对象,允许我们进行读写操作。它接受两个主要参数:文件路径和模式(r
、w
、a
等)。
# 以只读模式打开文件
file = open("example.txt", "r")
常见的文件打开模式:
r
:只读模式(默认),如果文件不存在则会抛出错误。w
:写入模式,文件不存在时会创建文件,存在时会覆盖内容。a
:追加模式,文件不存在时会创建文件,存在时会在文件末尾追加内容。rb
:以二进制模式读取文件。wb
:以二进制模式写入文件。x
:排他性创建文件。如果文件已存在,会抛出异常。
关闭文件
在完成文件操作后,应该调用 close()
方法关闭文件。这是一个良好的编程习惯,有助于释放资源。
file.close()
2. 文件的读写
读取文件内容
-
read()
:一次性读取整个文件的内容。with open("example.txt", "r") as file: content = file.read() print(content)
-
readlines()
:将文件内容按行读取,返回一个列表,其中每一项是文件中的一行。with open("example.txt", "r") as file: lines = file.readlines() for line in lines: print(line.strip()) # 使用strip()去除每行的换行符
-
read(n)
:读取指定大小的内容(n
是字节数或字符数)。with open("example.txt", "r") as file: content = file.read(5) # 读取前5个字符 print(content)
写入文件内容
-
write()
:将字符串写入文件。注意,这不会自动添加换行符。with open("example.txt", "w") as file: file.write("Hello, World!")
-
writelines()
:将一个列表中的字符串逐行写入文件。with open("example.txt", "w") as file: lines = ["Hello\n", "World\n", "Python\n"] file.writelines(lines)
追加写入
如果你不想覆盖原文件内容而是追加内容,可以使用 a
模式。
with open("example.txt", "a") as file:
file.write("\nThis is an appended line.")
3. 文件读写应用示例
示例 1: 读取文件并修改内容
假设我们有一个文件 data.txt
,内容为多个数字,我们想读取文件,处理数字(例如加 1),然后写回文件。
# 读取文件中的数据,处理后写回文件
with open("data.txt", "r") as file:
numbers = file.readlines()
numbers = [str(int(num.strip()) + 1) + "\n" for num in numbers] # 假设每行是一个数字
with open("data.txt", "w") as file:
file.writelines(numbers)
示例 2: 统计文件中的单词数
假设我们要统计一个文件中所有单词的数量。
with open("text.txt", "r") as file:
text = file.read()
words = text.split() # 根据空格分隔单词
word_count = len(words)
print(f"Word count: {word_count}")
示例 3: 使用 with
语句打开文件(推荐方式)
使用 with
语句能够自动管理文件的打开和关闭,避免遗漏关闭文件的情况,是推荐的做法。
with open("example.txt", "r") as file:
content = file.read()
print(content)
4. 文件操作的注意事项
-
文件路径:在指定文件路径时,最好使用绝对路径或相对路径。如果文件在当前工作目录下,可以只写文件名。如果文件路径中包含空格或特殊字符,记得加引号。
-
异常处理:如果文件打开失败(比如文件不存在,或者没有读写权限),建议使用
try-except
语句捕获异常。try: with open("example.txt", "r") as file: content = file.read() except FileNotFoundError: print("文件未找到") except IOError: print("文件读取错误")
-
文件模式选择:对于文本文件,通常使用
r
,w
,a
模式,而对于二进制文件(如图像文件),使用rb
,wb
模式。
总结
- 使用
open()
打开文件,操作完文件后记得使用close()
关闭文件。- 读取文件可用
read()
,readlines()
, 或read(n)
方法,写入文件可用write()
或writelines()
。- 使用
with
语句是打开文件的推荐方式,它可以自动关闭文件。- 使用适当的文件模式(如
r
,w
,a
)进行读写操作。