You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python按每5行拆分数据并写入动态命名多文件

问题说明

给定test.csv文件内容如下:

name,age,n1,n2,n3
a,21,1,2,3
b,22,4,9,0
c,25,4,5,6
d,25,41,5,6
e,25,4,66,6
f,25,4,5,66
g,25,4,55,6
h,25,4,5,56
i,25,41,5,61
j,25,4,51,60
k,20,40,50,60
l,21,40,51,60

已编写的读取数据并存入字典的代码:

import pandas as pd

input_file = pd.read_csv("test.csv")
for i in range(0, len(input_file['name'])):   
    dict1 = {}
    dict1["name"] = str(input_file['name'][i])
    dict1["age"] = str(input_file['age'][i])
    dict1["n1"] = str(input_file['n1'][i])
    dict1["n2"] = str(input_file['n2'][i])
    dict1["n3"] = str(input_file['n3'][i]) 

需要实现的需求:

  • 将数据按每5行拆分生成多个文件
  • 必须使用Python的writelines函数处理字典数据
  • 文件名需动态生成
  • 适配动态输入数据(行数可能变化)

预期输出示例:

out_file = open('File1.xml', 'w')
out_file.writelines(处理后的字典行数据)
out_file.writelines("\n")

对应生成的文件内容:

  • File1内容:
a,21,1,2,3
b,22,4,9,0
c,25,4,5,6
d,25,41,5,6
e,25,4,66,6
  • File2内容:
f,25,4,5,66
g,25,4,55,6
h,25,4,5,56
i,25,41,5,61
j,25,4,51,60
  • File3内容:
k,20,40,50,60
l,21,40,51,60
解决方案代码
import pandas as pd

# 读取CSV数据
df = pd.read_csv("test.csv")
# 定义每批拆分的行数
batch_size = 5
# 计算总批次数量(适配动态行数)
total_batches = (len(df) + batch_size - 1) // batch_size

for batch_num in range(total_batches):
    # 计算当前批次的起止索引
    start_idx = batch_num * batch_size
    end_idx = start_idx + batch_size
    # 截取当前批次的数据
    batch_data = df.iloc[start_idx:end_idx]
    
    # 动态生成文件名
    filename = f"File{batch_num + 1}.xml"
    with open(filename, 'w', encoding='utf-8') as out_file:
        # 遍历当前批次的每一行
        for _, row in batch_data.iterrows():
            # 将行数据转为字典(与原有代码逻辑一致)
            row_dict = {
                "name": str(row['name']),
                "age": str(row['age']),
                "n1": str(row['n1']),
                "n2": str(row['n2']),
                "n3": str(row['n3'])
            }
            # 将字典值按顺序拼接为CSV格式行
            line = ','.join(row_dict.values()) + '\n'
            # 使用writelines写入文件
            out_file.writelines(line)
代码说明
  • 通过计算总批次数量,自动适配任意行数的输入数据
  • 每个批次对应一个动态命名的文件(File1.xml、File2.xml...)
  • 保留原有字典转换逻辑,将字典值拼接为要求的字符串格式后,用writelines写入
  • 使用with open上下文管理器自动处理文件关闭,避免资源泄漏

内容的提问来源于stack exchange,提问作者Dhananjaya D N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 07:17:41