鱼C论坛

 找回密码
 立即注册
查看: 107|回复: 1

[技术交流] 如何使用 Python 进行文件读写操作?

[复制链接]
发表于 2025-3-7 16:26:29 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
今天的内容来介绍 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 对象是可迭代的,每次迭代返回一行。

二、文件写入:
# 打开文件进行写入
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。

三、文件追加:
# 打开文件进行追加
with open('output.txt', 'a') as file:
    # 追加内容
    file.write("\nThis is an appended line.")

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

四、文件读写的二进制模式:
# 以二进制模式读取文件
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 文件:
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 文件:
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 库):
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 模块进行对象序列化和反序列化:
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 语句确保文件的正确打开和关闭。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2025-3-7 16:26:53 | 显示全部楼层
如何使用 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 打开文件。
    • with 语句:确保文件自动关闭。
    • file.read():读取文件的全部内容。
    • file.seek(0):将文件指针重置到文件开头。
    • file.readlines():按行读取文件内容,返回列表。
    • for line in file:逐行读取文件。

  • 二、文件写入:
    # 打开文件进行写入
    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():将内容写入文件。

  • 三、文件追加:
    # 打开文件进行追加
    with open('output.txt', 'a') as file:
        # 追加内容
        file.write("\nThis is an appended line.")

    代码解释:
    • open('output.txt', 'a'):以追加模式 a 打开文件。

  • 四、文件读写的二进制模式:
    # 以二进制模式读取文件
    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 打开文件。

  • 五、使用 json 模块读写 JSON 文件:
    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 对象序列化为 JSON 并写入文件。
    • json.load(file):读取 JSON 数据并解析为 Python 对象。

  • 六、使用 csv 模块读写 CSV 文件:
    import csv
    # 写入 CSV 数据
    data = [[1, 2, 3], [4, 5, 6]]
    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 模块读写文件:
    import pandas as pd
    
    # 写入数据到 CSV 文件
    data = {'Name': ['John', 'Anna'], '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):创建 DataFrame。
    • df.to_csv():将 DataFrame 存为 CSV 文件。
    • pd.read_csv():读取 CSV 文件。

  • 八、使用 pickle 模块进行对象序列化和反序列化:
    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):序列化并写入二进制文件。
    • pickle.load(file):读取二进制数据并反序列化。



总结:根据文件类型和操作需求,灵活使用 open 函数和相关模块(如 jsoncsvpandaspickle),并使用 with 语句确保文件正确打开和关闭。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-2 02:37

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表