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

前言

大家好,我是 孤客。今天的内容来介绍 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):将字典数据转换为 pandasDataFrame 对象。
  • 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 到了么,欢迎关注孤客编程,全栈路上我们并肩前行。

相关推荐
用户8356290780515 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户8356290780515 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生13 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师14 小时前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码14 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf14 小时前
FastAPI 如何连接 MySQL
后端·python
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780511 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent1 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6252 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python