文件读写常用操作

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
)
相关推荐
TextIn智能文档云平台2 小时前
图片转文字后怎么输入大模型处理
前端·人工智能·python
ujainu2 小时前
Python学习第一天:保留字和标识符
python·学习·标识符·保留字
sheji34162 小时前
【开题答辩全过程】以 基于Java的应急安全学习平台的设计与实现为例,包含答辩的问题和答案
java·开发语言·学习
studytosky2 小时前
深度学习理论与实战:反向传播、参数初始化与优化算法全解析
人工智能·python·深度学习·算法·分类·matplotlib
winfield8212 小时前
MCP 协议详解
开发语言·网络·qt
cheems95273 小时前
锁策略的介绍
java·开发语言
清水白石0083 小时前
《Python × 数据库:用 SQLAlchemy 解锁高效 ORM 编程的艺术》
开发语言·python·json
星依网络3 小时前
使用LabelImg工具标注数据(游戏辅助脚本开发)
python·游戏引擎·图形渲染·骨骼绑定