【问题标题】:trying to convert csv to xml , one xml file should get generated for each 15 records present in csv file试图将 csv 转换为 xml ,应该为 csv 文件中存在的每 15 条记录生成一个 xml 文件
【发布时间】:2022-08-17 17:45:49
【问题描述】:

我是 python 家族的新手,我正在尝试在我的 python 代码中将 csv 转换为 xml, 我想为 csv 文件中的每 15 条记录创建一个 xml 文件

import csv

file_path = open(\"test.csv\")
csv_file = csv.reader(file_path)
list1 = []

for record in csv_file :
list1.append(record)

file_path.close()

print(list1)

def convert_row(record):
return \"\"\"<AllData>
<first_clm>%s</first_clm>
<second_clm>%s</second_clm>
</AllData>\"\"\" % (record[0],record[1])


with open(\'output.xml\',\'w\') as f :
f.write(\'\\n\'.join(convert_row(record) for record in list1))      
  • 你写过代码吗?你有没有遇到任何错误?我们不能简单地为您编写该代码。请看How to Ask
  • 是的,我已经编写了代码,因为我生成了一个包含所有 csv 文件记录的单个 xml 文件
  • 这回答了你的问题了吗? Simple CSV to XML Conversion - Python

标签: python


【解决方案1】:

尝试以块的形式读取输入文件并将每个块迭代地转换为xml。例如,

import pandas as pd

chunksize = 15

def convert_xml(df):
    Row_list =[]
    # Iterate over each row
    for index, rows in df.iterrows():
        # Create list for the current row
        my_list =[rows.col_1, rows.col_2]
        # append the list to the final list
        Row_list.append(my_list)
    with open('path/to/output/file', 'w') as f:
        f.write('\n'.join(convert_row(record) for record in Row_list))

for chunk in pd.read_csv('path/to/file', chunksize=chunksize):
    convert_xml(chunk)

col_1col_2 替换为 csv 文件中的标题。

干杯!!

【讨论】:

  • 谢谢兄弟的回复,但是我已经尝试过了,但是如何将数据框转换为xml
  • @Ganesh 现在检查。我已经添加了相应的代码。基本上,打开块->将该块中的行写入列表->将列表转换为xml->对每个块重复。如果这有帮助,请投票。
猜你喜欢
  • 1970-01-01
  • 2011-03-05
  • 2015-10-28
  • 2014-11-22
  • 2017-04-18
  • 1970-01-01
  • 2020-03-21
  • 1970-01-01
相关资源
最近更新 更多