Python开发 —— 文件读写操作open与with open

在 Python 中,文件读写操作是非常常见的任务。本文是一些关键操作和代码示例,包括如何使用 `open`、`with open`、`read` 和 `write` 函数进行文件操作。

1. 打开文件 (open)

使用 open 函数打开文件。在 Python 中,打开文件是进行文件操作的第一步。使用 open 函数可以打开文件,并返回一个文件对象。这个文件对象可以用于后续的读写操作。

以下是关于 open 函数的详细解释和示例。

1.1 open 函数的基本语法

python 复制代码
file_object = open(file_name, mode)
  • file_name:文件的名称或路径(字符串)。

  • mode:文件打开的模式(字符串),常见模式如下:

  • `'r'`:只读模式。文件必须存在,否则会抛出 `FileNotFoundError`。

  • `'w'`:写入模式。若文件不存在,会创建一个新文件;若文件存在,会截断(清空)文件。

  • `'a'`:追加模式。若文件不存在,会创建一个新文件;若文件存在,写入的数据会追加到文件末尾。

  • `'b'`:二进制模式。可以与其他模式结合使用,如 `'rb'`(二进制只读),`'wb'`(二进制写入),`'ab'`(二进制追加)。

  • `'+'`:读写模式。可以与其他模式结合使用,如 `'r+'`(读写),`'w+'`(写读),`'a+'`(追加读写)。

1.2 示例

1.2.1 只读模式('r')

只读模式用于读取文件内容,文件必须存在。

python 复制代码
try:
    file = open('example.txt', 'r')
    print('File opened successfully')
except FileNotFoundError:
    print('File not found')
finally:
    file.close()

1.2.2 写入模式('w')

写入模式用于写入文件内容,如果文件存在,则会清空文件内容;如果文件不存在,则会创建一个新文件。

python 复制代码
file = open('example.txt', 'w')
file.write('This is a test.')
file.close()

1.2.3 追加模式('a')

追加模式用于在文件末尾追加内容,如果文件不存在,则会创建一个新文件。

python 复制代码
file = open('example.txt', 'a')
file.write('\nThis is an appended line.')
file.close()

1.2.4 二进制模式('b')

二进制模式用于处理非文本文件,如图像或其他二进制数据。

python 复制代码
# 二进制只读模式
file = open('example.jpg', 'rb')
data = file.read()
file.close()

# 二进制写入模式
file = open('example_copy.jpg', 'wb')
file.write(data)
file.close()
```

1.2.5 读写模式('+')

读写模式用于同时读取和写入文件。文件必须存在,除非使用写读模式('w+')或追加读写模式('a+')。

python 复制代码
# 读写模式(文件必须存在)
file = open('example.txt', 'r+')
content = file.read()
file.write('\nThis is added text.')
file.close()

# 写读模式(文件不存在会创建,存在则清空)
file = open('example.txt', 'w+')
file.write('This is new content.')
file.seek(0)
content = file.read()
file.close()

# 追加读写模式(文件不存在会创建,存在则追加)
file = open('example.txt', 'a+')
file.write('\nThis is appended content.')
file.seek(0)
content = file.read()
file.close()

2. with open

2.1 open 函数的基本语法

使用 with open 语句可以确保文件在使用后自动关闭,这是一种更安全的文件操作方式。

python 复制代码
with open('example.txt', 'r') as file:

    # 进行文件操作
    content = file.read()
    print(content)
# 在 with 语句块结束后,文件会自动关闭

2.2 详细示例

以下是一个更详细的示例,展示了不同模式下如何打开文件:

python 复制代码
# 示例:只读模式(文件必须存在)
try:
    with open('example.txt', 'r') as file:
        content = file.read()
        print('Read content:', content)
except FileNotFoundError:
    print('File not found')

# 示例:写入模式(会覆盖现有文件)
with open('example.txt', 'w') as file:
    file.write('New content written.\n')

# 示例:追加模式(追加到现有文件末尾)
with open('example.txt', 'a') as file:
    file.write('This line is appended.\n')

# 示例:二进制模式读取和写入
with open('example.jpg', 'rb') as file:
    binary_data = file.read()

with open('example_copy.jpg', 'wb') as file:
    file.write(binary_data)

# 示例:读写模式(文件必须存在)
try:
    with open('example.txt', 'r+') as file:
        content = file.read()
        print('Original content:', content)
        file.write('Additional content.\n')
except FileNotFoundError:
    print('File not found')

# 示例:写读模式(文件不存在会创建)
with open('example.txt', 'w+') as file:
    file.write('New content.\n')
    file.seek(0)
    content = file.read()
    print('Written and read content:', content)

# 示例:追加读写模式(文件不存在会创建)
with open('example.txt', 'a+') as file:
    file.write('Appended content.\n')
    file.seek(0)
    content = file.read()
    print('Appended and read content:', content)

通过这些示例,您可以深入理解如何在 Python 中使用不同模式打开和操作文件,确保正确读写文件内容并安全关闭文件。

3. 对比 open 和 with open

在 Python 中,`open` 和 `with open` 都可以用于打开文件,但它们在处理文件的方式和资源管理上有显著区别。以下是两者的详细对比:

3.1 open 函数

open 函数是最基础的文件打开方法。使用 open 函数打开文件后,必须显式调用 close 方法关闭文件,以释放资源。如果忘记关闭文件,可能会导致资源泄漏或文件被锁定。

3.1.1 优点

更加灵活,可以手动控制文件的打开和关闭。

适用于需要复杂文件操作的场景。

3.1.2 缺点

容易忘记调用 close 方法,导致资源泄漏。

需要额外的代码来确保文件在出现异常时也能被正确关闭。

3.1.3 示例

python 复制代码
try:
    file = open('example.txt', 'r')
    content = file.read()
    print(content)
finally:
    file.close()  # 确保文件被关闭

在这个例子中,文件必须在 try 块结束后显式关闭,即使在读取文件过程中发生异常也要关闭文件。这种显式管理文件资源的方法增加了代码的复杂性。

3.2 with open 语句

with open语句是上下文管理器的一部分,确保文件在使用结束后自动关闭。with open 语句简化了文件操作,避免了显式调用 close 方法,即使发生异常,文件也会被正确关闭。

3.2.1 优点

自动管理文件资源,确保文件被正确关闭。

代码更简洁,减少了管理文件资源的代码量。

更安全,避免了资源泄漏。

3.2.2 缺点

对于需要非常复杂的文件管理场景,可能不如 `open` 函数灵活。

3.2.3 示例

python 复制代码
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)
# 文件会在 with 语句块结束后自动关闭

在这个例子中,with open 语句确保文件在读取完内容后自动关闭,即使在读取过程中发生异常也是如此。这样减少了显式管理文件资源的复杂性。

3.3 对比总结

特性 open with open
文件关闭管理 需要显式调用 `close` 方法 自动关闭文件
代码简洁性 需要更多代码管理文件资源 更加简洁
异常处理 需要额外的代码确保文件在异常时关闭 自动处理异常
灵活性 适用于复杂的文件操作 适用于大多数文件操作场景

3.4 实践中的对比

3.4.1 使用 open 管理文件资源

python 复制代码
try:
    file = open('example.txt', 'r')
    content = file.read()
    print(content)
finally:
    file.close()  # 确保文件被关闭

这个例子中,显式调用 file.close() 确保文件被正确关闭,但增加了代码量和复杂性。

3.4.2 使用 with open 管理文件资源

python 复制代码
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)
# 文件会在 with 语句块结束后自动关闭

这个例子中,with open 自动管理文件关闭,代码更简洁、安全。

3.5 结论

在大多数情况下,推荐使用 with open 语句来打开文件,因为它能自动管理文件资源,确保文件在使用结束后被正确关闭,减少了资源泄漏的风险和代码的复杂性。然而,对于需要非常复杂的文件操作场景,可能需要使用 open 函数进行更精细的控制。

4. 读取文件 (read)

可以使用 `read` 方法读取文件的内容。常见的读取方法包括:

read():读取整个文件。

readline():读取文件中的一行。

readlines():读取文件中的所有行,并返回一个列表。

4.1 示例

读取整个文件的内容:

python 复制代码
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

读取文件中的一行:

python 复制代码
with open('example.txt', 'r') as file:
    line = file.readline()
    print(line)

读取文件中的所有行:

python 复制代码
with open('example.txt', 'r') as file:
    lines = file.readlines()
    for line in lines:
        print(line)

5. 写入文件 (write)

可以使用 write 方法将数据写入文件。注意,如果文件以 w 模式打开,写入操作会覆盖文件的现有内容。

5.1 示例

写入字符串到文件:

python 复制代码
with open('example.txt', 'w') as file:
    file.write('Hello, World!')

追加字符串到文件:

python 复制代码
with open('example.txt', 'a') as file:
    file.write('\nHello again!')

写入多行数据:

python 复制代码
lines = ['First line\n', 'Second line\n', 'Third line\n']
with open('example.txt', 'w') as file:
    file.writelines(lines)

6. 综合示例

以下是一个综合示例,展示了如何打开文件、读取文件内容、写入文件内容以及使用 with open 语句。

python 复制代码
# 读取文件内容
with open('example.txt', 'r') as file:
    content = file.read()
    print('File content before writing:')
    print(content)

# 写入新内容到文件(覆盖模式)
with open('example.txt', 'w') as file:
    file.write('New content line 1\n')
    file.write('New content line 2\n')

# 追加内容到文件
with open('example.txt', 'a') as file:
    file.write('Appended line 1\n')
    file.write('Appended line 2\n')

# 再次读取文件内容
with open('example.txt', 'r') as file:
    new_content = file.read()
    print('File content after writing:')
    print(new_content)

通过这些示例,您可以了解如何在 Python 中进行文件的读写操作,包括如何安全地打开和关闭文件,以及如何读取和写入文件内容。

相关推荐
数据智能老司机6 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机7 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机7 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机7 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i7 小时前
drf初步梳理
python·django
每日AI新事件7 小时前
python的异步函数
python
这里有鱼汤9 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
databook18 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室18 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三20 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试