Python文件操作:创建、写入、读取和高级技巧109


Python 提供了强大的文件操作能力,能够轻松地创建、写入、读取和修改文件。本文将详细介绍 Python 中的文件操作方法,涵盖基础知识和一些高级技巧,帮助你熟练掌握 Python 文件处理。

一、创建文件

在 Python 中,创建文件最常用的方法是使用 open() 函数,并指定文件模式为 'x' (exclusive creation)。如果文件已存在,则会抛出 FileExistsError 异常。 如果文件不存在,则会创建一个新文件。```python
try:
file = open("", "x")
() # 记得关闭文件
print("文件 '' 创建成功")
except FileExistsError:
print("文件 '' 已存在")
```

需要注意的是,仅仅使用 open("", "x") 并不会写入任何内容到文件中,它仅仅是创建了一个空文件。要写入内容,需要使用其他的文件模式。

二、写入文件

使用 open() 函数,并指定文件模式为 'w' (write) 可以写入文件。如果文件不存在,则会创建一个新文件;如果文件存在,则会覆盖原文件内容。```python
with open("", "w") as file:
("Hello, world!")
("This is a new line.")
```

使用 with open(...) as file: 语句是一种推荐的写法,它会在代码块执行完毕后自动关闭文件,即使发生异常也能保证文件被正确关闭,避免资源泄漏。 代表换行符。

如果想在不覆盖原文件内容的情况下追加内容,可以使用 'a' (append) 模式:```python
with open("", "a") as file:
("This is appended text.")
```

三、读取文件

读取文件可以使用 open() 函数,并指定文件模式为 'r' (read)。默认情况下,open() 函数使用 'r' 模式。```python
with open("", "r") as file:
contents = () # 读取整个文件内容
print(contents)
with open("", "r") as file:
for line in file: # 按行读取文件内容
print(line, end="") # end="" 去除多余的换行符
```

() 会将整个文件内容读取到一个字符串中。而迭代文件对象(for line in file:) 会按行读取文件内容,更适合处理大型文件,避免内存溢出。

四、处理不同类型的文件

Python 可以处理各种类型的文件,包括文本文件、CSV 文件、JSON 文件等等。对于不同的文件类型,需要使用不同的方法进行读取和写入。

CSV 文件: 使用 csv 模块```python
import csv
with open("", "w", newline="") as csvfile:
writer = (csvfile)
(["Name", "Age", "City"])
(["Alice", "25", "New York"])
(["Bob", "30", "London"])
with open("", "r") as csvfile:
reader = (csvfile)
for row in reader:
print(row)
```

JSON 文件: 使用 json 模块```python
import json
data = {"name": "Alice", "age": 25, "city": "New York"}
with open("", "w") as jsonfile:
(data, jsonfile, indent=4) # indent参数用于格式化输出
with open("", "r") as jsonfile:
data = (jsonfile)
print(data)
```

五、异常处理

文件操作可能会发生各种异常,例如文件不存在、权限不足等等。使用 try...except 块可以处理这些异常,避免程序崩溃。```python
try:
with open("", "r") as file:
contents = ()
except FileNotFoundError:
print("文件不存在")
except Exception as e:
print(f"发生错误: {e}")
```

六、高级技巧

1. 文件路径操作: 使用 os 模块可以方便地进行文件路径操作,例如创建目录、获取文件信息等。```python
import os
("mydir", exist_ok=True) # 创建目录,exist_ok=True 避免异常
print(("")) # 检查文件是否存在
```

2. 缓冲区: 对于大型文件,可以使用缓冲区提高写入效率。```python
with open("", "wb") as f:
buffer = bytearray(1024 * 1024) # 1MB 缓冲区
while True:
data = some_function_to_read_data() # 从其他地方读取数据
if not data:
break
(data)
```

3. 上下文管理器: with open(...) as file: 语句就是一种上下文管理器,确保文件在使用完毕后被正确关闭。可以自定义上下文管理器来管理其他资源。

掌握以上内容,你就能熟练地使用 Python 进行各种文件操作,高效地处理各种数据。

2025-04-16


上一篇:深入探索Python文件夹操作:高级技巧与最佳实践

下一篇:Python文件特定行操作:读取、写入、修改及高级技巧