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 中进行文件的读写操作,包括如何安全地打开和关闭文件,以及如何读取和写入文件内容。

相关推荐
Envyᥫᩣ5 分钟前
Python中的自然语言处理:从基础到高级
python·自然语言处理·easyui
哪 吒6 分钟前
华为OD机试 - 几何平均值最大子数(Python/JS/C/C++ 2024 E卷 200分)
javascript·python·华为od
我是陈泽9 分钟前
一行 Python 代码能实现什么丧心病狂的功能?圣诞树源代码
开发语言·python·程序员·编程·python教程·python学习·python教学
hakesashou10 分钟前
python全栈开发是什么?
python
优雅的小武先生20 分钟前
QT中的按钮控件和comboBox控件和spinBox控件无法点击的bug
开发语言·qt·bug
虽千万人 吾往矣26 分钟前
golang gorm
开发语言·数据库·后端·tcp/ip·golang
创作小达人29 分钟前
家政服务|基于springBoot的家政服务平台设计与实现(附项目源码+论文+数据库)
开发语言·python
郭二哈31 分钟前
C++——list
开发语言·c++·list
杨荧32 分钟前
【JAVA开源】基于Vue和SpringBoot的洗衣店订单管理系统
java·开发语言·vue.js·spring boot·spring cloud·开源
ZPC821039 分钟前
Python使用matplotlib绘制图形大全(曲线图、条形图、饼图等)
开发语言·python·matplotlib