Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Hi, I want to convert below XML to CSV using python. Below is my code. But throwing an error while running for below xml. Please
Hi, I want to convert below XML to CSV using python. Below is my code. But throwing an error while running for below xml. Please help.
Python Code:
import xml.etree.ElementTree as ET import sys import csv def xml_to_csv(xml_filename, output_csv): tree = ET.parse(xml_filename) root = tree.getroot() xml_data_to_csv = open(output_csv, 'w') csvwriter = csv.writer(xml_data_to_csv, quotechar="'", lineterminator=' ') header_added = False header = [] for row in root.findall('row'): attributes = row.attrib csv_row = [] for key, value in attributes.items(): if not header_added: header.append(key) csv_row.append('"%s"' % str(value)) if not header_added: csvwriter.writerow(header) header_added = True csvwriter.writerow(csv_row) xml_data_to_csv.close() if __name__ == '__main__': for filename in sys.argv[1:]: xml_to_csv(filename, "%s.csv" % filename) # filename + ".csv"
Error:
csv_row.append('"%s"' % str(value)) UnicodeEncodeError: 'ascii' codec can't encode character u'\u0101' in position 1: ordinal not in range(128)
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started