文件读写常用操作

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
)
相关推荐
MaoziShan4 分钟前
[ICLR 2026] 一文读懂 AutoGEO:生成式搜索引擎优化(GEO)的自动化解决方案
人工智能·python·搜索引擎·语言模型·自然语言处理·内容运营·生成式搜索引擎
一切尽在,你来10 分钟前
C++多线程教程-1.2.2 C++标准库并发组件的设计理念
开发语言·c++
2401_8384725118 分钟前
使用Python处理计算机图形学(PIL/Pillow)
jvm·数据库·python
m0_5613596720 分钟前
代码热更新技术
开发语言·c++·算法
兩尛26 分钟前
c++知识点1
java·开发语言·c++
凯子坚持 c26 分钟前
Qt常用控件指南(9)
开发语言·qt
深蓝电商API27 分钟前
aiohttp爬取带登录态的异步请求
爬虫·python
ONE_PUNCH_Ge27 分钟前
Go 语言泛型
开发语言·后端·golang
rainbow688930 分钟前
Python学生管理系统:JSON持久化实战
java·前端·python