文件读写常用操作

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
)
相关推荐
爱吃程序猿的喵几秒前
LingBot-Map 复现与原理剖析:基于 Geometric Context Transformer 的流式 3D 重建
人工智能·python·深度学习·计算机视觉·3d·transformer
梦想不只是梦与想1 分钟前
Python 中的 match-case(模式匹配)
python·match-case
郝同学今天有进步吗4 分钟前
构建 LangGraph Code Review Agent(四):文件过滤与 AnalysisPackage 分包
git·python·ai·code review
a11177610 分钟前
基于PyTorch的动物图像识别系统 开源
人工智能·pytorch·python
qetfw16 分钟前
MWU:Vue 3 + FastAPI 的 MaaFramework 跨平台 WebUI 源码
前端·vue.js·python·fastapi·开源项目·效率工具
a44931536221 分钟前
MacBook USB-C不充电故障诊断:从PD握手到主板供电链路
c语言·开发语言·macos·电脑
测试老哥23 分钟前
接口自动化测试分层设计与实践总结
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
德福危险29 分钟前
从目录枚举到bash破壳漏洞、从流量抓包到组权限提权:靶机练习之symfonos3
开发语言·bash
meng半颗糖34 分钟前
3.Java流程控制语句
java·开发语言·intellij-idea
影寂ldy39 分钟前
C# WinForm 三种自定义控件 + 完全自定义重绘控件知识点
开发语言·c#