Skip to content

Python 文件处理

文件处理是任何编程语言中都不可或缺的一部分。Python 提供了简单而强大的内置功能来创建、读取和写入文件。

打开文件: open()

要对文件进行操作,你必须先使用 open() 函数打开它。open() 函数会返回一个文件对象。

基本语法:file_object = open(file_name, mode)

  • file_name: 你想要打开的文件的路径。
  • mode: 一个字符串,指定你打算如何操作文件。

文件模式 (Mode)

模式描述
'r'读取 (Read) - 默认模式。如果文件不存在,会引发 FileNotFoundError
'w'写入 (Write) - 打开文件用于写入。如果文件存在,其内容会被清空;如果文件不存在,则会创建一个新文件。
'a'追加 (Append) - 打开文件用于写入,但新的内容会追加到文件末尾,而不会清空原有内容。如果文件不存在,则会创建一个新文件。
'r+'读写 - 打开文件用于读取和写入。
'b'二进制模式 (Binary) - 可以与 r, w, a 结合使用(如 'rb', 'wb'),用于处理非文本文件(如图片、音频)。
't'文本模式 (Text) - 默认模式。可以与 r, w, a 结合使用。

使用 with 语句

处理文件时,最佳实践是使用 with 语句。with 语句可以确保在代码块执行完毕后,即使发生错误,文件也能被正确地关闭。

python
with open('example.txt', 'w') as f:
    f.write('Hello, World!\n')
    f.write('This is a new line.\n')

# 当 with 代码块结束时,文件 f 会被自动关闭。

读取文件

有几种方法可以从文件中读取内容。

假设我们有 example.txt 文件,内容如下:

Hello, World!
This is a new line.
And another one.

file.read()

读取文件的全部内容,并将其作为一个单一的字符串返回。

python
with open('example.txt', 'r') as f:
    content = f.read()
    print(content)

file.readline()

一次只读取文件的一行(包括行尾的换行符 \n),并将其作为字符串返回。

python
with open('example.txt', 'r') as f:
    line1 = f.readline()
    line2 = f.readline()
    print(f"Line 1: {line1.strip()}") # .strip() 移除首尾空白
    print(f"Line 2: {line2.strip()}")

file.readlines()

读取文件的所有行,并将它们作为字符串列表返回。列表中的每个字符串都代表文件中的一行。

python
with open('example.txt', 'r') as f:
    lines = f.readlines()
    print(lines)
    # 输出: ['Hello, World!\n', 'This is a new line.\n', 'And another one.\n']

直接遍历文件对象

这是最常用、最高效的逐行读取文件的方式,因为它不会一次性将所有行加载到内存中。

python
with open('example.txt', 'r') as f:
    for line in f:
        print(line.strip()) # strip() 用于移除换行符

写入文件

file.write(string)

将一个字符串写入文件。这个方法不会自动添加换行符,你需要手动添加 \n

python
with open('output.txt', 'w') as f:
    f.write('First line.\n')
    f.write('Second line.\n')

file.writelines(list_of_strings)

将一个字符串列表写入文件。同样,它也不会自动添加换行符。

python
lines_to_write = ['Header\n', 'Data line 1\n', 'Data line 2\n']
with open('data.txt', 'w') as f:
    f.writelines(lines_to_write)

本站内容仅供学习和研究使用。