文件读写常用操作

json文件

{"name": "John", "age": 30}, {"name": "Jane", "age": 25}, {"name": "Bob", "age": 40}

jsonl文件

{"name": "John", "age": 30}

{"name": "Jane", "age": 25}

{"name": "Bob", "age": 40}

python 复制代码
import json
jsonl_file="b.jsonl"
json_file="a.json"
output_jsonl="c.jsonl"
with open(jsonl_file, "r", encoding="utf-8") as f_in, open(output_jsonl, "w", encoding="utf-8") as f_out:
    for idx, line in enumerate(f_in):
        data = json.loads(line)
        question_text = data.get("question", "")
        image_dir = data.get("image", "")
        audio_dir = data.get("audio", "")
        f_out.write(json.dumps(data, ensure_ascii=False) + "\n") #写jsonl文件
with open(json_file, "r", encoding="utf-8") as f_in, open(output_jsonl, "w", encoding="utf-8") as f_out:
    data = json.load(f_in)
    t=[]
    for i in data:
        print(i)
        t.append(i)
with open("data.json", "w") as f:
    json.dump(t, f)

txt文件读写

python 复制代码
with open('f.txt', 'r') as file:
    # content = file.read()
    for i,j in enumerate(file):
        print(i,j)
    # print(content)
# 写入文本
with open('file.txt', 'w') as file:
    file.write('Hello, world!')

excel文件

python 复制代码
import pandas as pd

# ===== Excel 读写 =====
df_excel = pd.read_excel(
    'data/Data_Dictionary.xlsx',
    sheet_name='train',
    header=2
)

# 遍历每一行(推荐方式)
for idx, row in df_excel.iterrows():
    # 示例:访问某一列
    # value = row['column_name']
    print(idx, row.to_dict())

# 写入 Excel
df_excel.to_excel(
    'data/output.xlsx',
    index=False
)

csv文件

python 复制代码
import pandas as pd
# ===== CSV 读写 =====
df_csv = pd.read_csv(
    'data/sample_submission.csv',
    header=0
)

# 遍历每一行
for idx, row in df_csv.iterrows():
    print(idx, row.to_dict())

# 查看前 5 行
print(df_csv.head(5))

# 写入 CSV
df_csv.to_csv(
    'data/output.csv',
    index=False
)
相关推荐
程序之巅16 小时前
VS code 远程python代码debug
android·java·python
liulilittle16 小时前
XDP VNP虚拟以太网关(章节:一)
linux·服务器·开发语言·网络·c++·通信·xdp
我不是8神16 小时前
Qt 知识点全面总结
开发语言·qt
Ralph_Y16 小时前
多重继承与虚继承
开发语言·c++
__如风__16 小时前
onlyoffice文档转换服务离线部署
python
今晚务必早点睡16 小时前
写一个Python接口:发送支付成功短信
开发语言·python
jghhh0116 小时前
基于C#实现与三菱FX系列PLC串口通信
开发语言·算法·c#·信息与通信
ada7_16 小时前
LeetCode(python)22.括号生成
开发语言·数据结构·python·算法·leetcode·职场和发展
2501_9418714516 小时前
面向微服务链路追踪与全局上下文管理的互联网系统可观测性设计与多语言工程实践分享
大数据·数据库·python
luoluoal16 小时前
基于python的语音和背景音乐分离算法及系统(源码+文档)
python·mysql·django·毕业设计·源码