文件读写常用操作

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
)
相关推荐
AI攻城狮17 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽18 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程2 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪2 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook2 天前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田2 天前
使用 pkgutil 实现动态插件系统
python