|
| 1 | +from xmltodict import parse as parseXML |
| 2 | +from csv import writer as CSVWriter |
| 3 | +from json import loads, dumps |
| 4 | +from sys import argv |
| 5 | + |
| 6 | + |
| 7 | +# validated the ammout of args passed from the command line, so I could get the path from both files before starting the script |
| 8 | +def getInputAndOutputFiles(): |
| 9 | + if len(argv) == 1: |
| 10 | + xmlPath = input("please enter the path to your JSON file: ") |
| 11 | + csvPath = input("please enter the path to your YAML file: ") |
| 12 | + elif len(argv) == 2: |
| 13 | + xmlPath = argv[1] |
| 14 | + csvPath = input("please enter the path to your YAML file: ") |
| 15 | + elif len(argv) >= 3: |
| 16 | + xmlPath = argv[1] |
| 17 | + csvPath = argv[2] |
| 18 | + return xmlPath, csvPath |
| 19 | + |
| 20 | + |
| 21 | +xmlPath, csvPath = getInputAndOutputFiles() |
| 22 | + |
| 23 | +print("started to convert your file...") |
| 24 | + |
| 25 | +# from line 31 to 35 |
| 26 | +# I read the file from the xmlPath variable, and got the dictory from parseXML |
| 27 | +# After that I got the first key from the dict (asumming the user passed a single xml liked the test.xml file) |
| 28 | +# After that I got the list of nodes inside the "root" |
| 29 | +# And finally I close the file |
| 30 | +def getChildNodesFromRoot(): |
| 31 | + with open(xmlPath, "r") as xmlFile: |
| 32 | + data_dict = parseXML(xmlFile.read()) |
| 33 | + data_root = data_dict[list(data_dict.keys())[0]] |
| 34 | + itemsList = list(data_root.values())[0] |
| 35 | + return itemsList |
| 36 | + |
| 37 | +itemsList = getChildNodesFromRoot() |
| 38 | +# Declared a csvWrite (object to write rows on a csv file) |
| 39 | +csvFile = open(csvPath, "w") |
| 40 | +csvWriter = CSVWriter(csvFile) |
| 41 | + |
| 42 | + |
| 43 | +# from line 49 to 57 |
| 44 | +# I iterated over all the items on the child of the file root |
| 45 | +# After that i made the variable item into a real dict so I could use |
| 46 | +# .keys and .values, the keys for the header row |
| 47 | +# and the values for all other rows on our csv' |
| 48 | + |
| 49 | +count = 0 |
| 50 | +for item in itemsList: |
| 51 | + item = loads(dumps(item)) |
| 52 | + if count == 0: |
| 53 | + header = item.keys() |
| 54 | + csvWriter.writerow(header) |
| 55 | + count += 1 |
| 56 | + csvWriter.writerow(item.values()) |
| 57 | +csvFile.close() |
| 58 | + |
| 59 | +print(f"done, your file is now on {csvPath}") |
0 commit comments