I am new to python family I am trying to convert csv to xml in my python code,
Asked
Active
Viewed 131 times
0
-
3Have you written any code? Have you encountered any errors? We can't simply write that code for you. Please see [ask] – Ofer Sadan Aug 17 '22 at 09:11
-
yes, I have written code, in that I have generated one single xml file with all csv file records – PVG Aug 17 '22 at 09:15
-
actually I have done that part, need help other than that @rzlvmp – PVG Aug 17 '22 at 10:22
2 Answers
1
Try reading your input file in chunks and convert each chunk to xml
iteratively. For example,
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)
replace col_1
and col_2
with headers in your csv file.
Cheers!!

botaskay
- 144
- 1
- 1
- 7
-
thank you brother for reply, but I have tried this but then how to convert dataframe to xml – PVG Aug 17 '22 at 09:32
-
@Ganesh Check now. I have added the corresponding code. Basically, open the chunk -> write rows in that chunk to list -> convert list to xml -> repeat for every chunk. Do upvote if this helps. – botaskay Aug 17 '22 at 09:39
-
Brother, I have csv file col_1,col_2 1,101 2,102 .... 100,200 and currently I am getting last 10 records in generated XML file
91 191 100 200
0
If I undesrtand correctly, your code is working correctly but you have only one XML file with last chunk info.
It happens because you loop over chunks and rewrite result.xml
at every iteration.
Just change file name for every chunk:
...
def convert_xml(df, file_name):
...
with open(file_name, 'w') as f:
f.write(...)
idx = 1
for chunk in csv_file:
convert_xml(chunk, f'result_{idx}.xml')
idx += 1

rzlvmp
- 7,512
- 5
- 16
- 45