如何使用 Python 进行文件读写操作?

beat365官方入口素描网 📅 2026-07-25 06:26:26 👤 admin 👁️ 8322 ❤️ 485
如何使用 Python 进行文件读写操作?

大家好,我是 V 哥。今天的内容来介绍 Python 中进行文件读写操作的方法,这在学习 Python 时是必不可少的技术点,希望可以帮助到正在学习 python的小伙伴。

以下是 Python 中进行文件读写操作的基本方法:

**一、文件读取**:

```python

# 打开文件

with open('example.txt', 'r') as file:

# 读取文件的全部内容

content = file.read()

print(content)

# 将文件指针重置到文件开头

file.seek(0)

# 逐行读取文件内容

lines = file.readlines()

for line in lines:

print(line.strip()) # 去除行末的换行符

# 将文件指针重置到文件开头

file.seek(0)

# 逐行读取文件内容的另一种方式

for line in file:

print(line.strip())

```

**代码解释**:

- `open('example.txt', 'r')`:以只读模式 `r` 打开名为 `example.txt` 的文件。

- `with` 语句:确保文件在使用完毕后自动关闭,避免资源泄漏。

- `file.read()`:读取文件的全部内容。

- `file.seek(0)`:将文件指针重置到文件开头,以便重新读取。

- `file.readlines()`:将文件内容按行读取,并存储在一个列表中,每一行是列表的一个元素。

- `for line in file`:逐行读取文件内容,`file` 对象是可迭代的,每次迭代返回一行。

**二、文件写入**:

```python

# 打开文件进行写入

with open('output.txt', 'w') as file:

# 写入内容

file.write("Hello, World!\n")

file.write("This is a new line.")

```

**代码解释**:

- `open('output.txt', 'w')`:以写入模式 `w` 打开文件,如果文件不存在,会创建文件;如果文件存在,会清空原文件内容。

- `file.write()`:将指定内容写入文件,不会自动添加换行符,若需要换行,需手动添加 `\n`。

**三、文件追加**:

```python

# 打开文件进行追加

with open('output.txt', 'a') as file:

# 追加内容

file.write("\nThis is an appended line.")

```

**代码解释**:

- `open('output.txt', 'a')`:以追加模式 `a` 打开文件,在文件末尾添加新内容,不会覆盖原文件内容。

**四、文件读写的二进制模式**:

```python

# 以二进制模式读取文件

with open('example.bin', 'rb') as file:

binary_data = file.read()

print(binary_data)

# 以二进制模式写入文件

with open('output.bin', 'wb') as file:

binary_data = b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64' # 二进制数据

file.write(binary_data)

```

**代码解释**:

- `open('example.bin', 'rb')`:以二进制只读模式 `rb` 打开文件。

- `open('output.bin', 'wb')`:以二进制写入模式 `wb` 打开文件。

- `b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64'`:表示二进制数据,使用 `b` 前缀。

**五、使用 `json` 模块读写 JSON 文件**:

```python

import json

# 写入 JSON 数据

data = {'name': 'John', 'age': 30, 'city': 'New York'}

with open('data.json', 'w') as file:

json.dump(data, file)

# 读取 JSON 数据

with open('data.json', 'r') as file:

loaded_data = json.load(file)

print(loaded_data)

```

**代码解释**:

- `json.dump(data, file)`:将 Python 对象 `data` 序列化为 JSON 格式并写入文件。

- `json.load(file)`:从文件中读取 JSON 数据并解析为 Python 对象。

**六、使用 `csv` 模块读写 CSV 文件**:

```python

import csv

# 写入 CSV 数据

data = [['Name', 'Age', 'City'], ['John', 30, 'New York'], ['Jane', 25, 'Chicago']]

with open('data.csv', 'w', newline='') as file:

writer = csv.writer(file)

writer.writerows(data)

# 读取 CSV 数据

with open('data.csv', 'r') as file:

reader = csv.reader(file)

for row in reader:

print(row)

```

**代码解释**:

- `csv.writer(file)`:创建一个 CSV 写入对象,将数据列表写入文件。

- `writer.writerows(data)`:将数据列表中的每一行写入文件。

- `csv.reader(file)`:创建一个 CSV 读取对象,逐行读取文件。

**七、使用 `pandas` 模块读写文件(需要安装 `pandas` 库)**:

```python

import pandas as pd

# 写入数据到 CSV 文件

data = {'Name': ['John', 'Jane'], 'Age': [30, 25], 'City': ['New York', 'Chicago']}

df = pd.DataFrame(data)

df.to_csv('data_pandas.csv', index=False)

# 读取 CSV 文件

df_read = pd.read_csv('data_pandas.csv')

print(df_read)

```

**代码解释**:

- `pd.DataFrame(data)`:将字典数据转换为 `pandas` 的 `DataFrame` 对象。

- `df.to_csv('data_pandas.csv', index=False)`:将 `DataFrame` 对象存储为 CSV 文件,不保存索引。

- `pd.read_csv('data_pandas.csv')`:读取 CSV 文件为 `DataFrame` 对象。

**八、使用 `pickle` 模块进行对象序列化和反序列化**:

```python

import pickle

# 序列化对象

data = {'name': 'John', 'age': 30, 'city': 'New York'}

with open('data.pkl', 'wb') as file:

pickle.dump(data, file)

# 反序列化对象

with open('data.pkl', 'rb') as file:

loaded_data = pickle.load(file)

print(loaded_data)

```

**代码解释**:

- `pickle.dump(data, file)`:将 Python 对象 `data` 序列化为二进制数据并写入文件。

- `pickle.load(file)`:从文件中读取二进制数据并反序列化为 Python 对象。

以上是 Python 中进行文件读写操作的常用方法,你可以根据不同的文件类型和使用场景,选择合适的方法进行操作。

**最后**

根据文件类型和操作需求,可以灵活使用内置的 open 函数及相关模块,如 json、csv、pandas 和 pickle 等,同时利用 with 语句确保文件的正确打开和关闭。你 Get 到了么,欢迎关注威哥爱编程,全栈路上我们并肩前行。

相关养生推荐

研究生延期毕业通常需要多长时间?
beat365官方入口素描网

研究生延期毕业通常需要多长时间?

📅 10-15 👁️ 7630
微信文件多久可撤回?官方回应
国内在365投注

微信文件多久可撤回?官方回应

📅 09-28 👁️ 7707
顺丰每天发车几趟的时间点
国内在365投注

顺丰每天发车几趟的时间点

📅 09-30 👁️ 8553
淝畔绿洲景区
beat365官方入口素描网

淝畔绿洲景区

📅 07-13 👁️ 5957