Skip to content

Commit 5843e13

Browse files
author
David Mendoza
committed
added some helper functions that where asked on other PR I made
1 parent cc4c546 commit 5843e13

File tree

1 file changed

+23
-20
lines changed

1 file changed

+23
-20
lines changed

Scripts/Miscellaneous/xml2csv/xml2csv.py

+23-20
Original file line numberDiff line numberDiff line change
@@ -3,41 +3,44 @@
33
from json import loads, dumps
44
from sys import argv
55

6-
xmlPath = ""
7-
csvPath = ""
86

97
# 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
1019

11-
if len(argv) == 1:
12-
xmlPath = input("please enter the path to your XML file: ")
13-
csvPath = input("please enter the path to your CSV file: ")
14-
elif len(argv) == 2:
15-
xmlPath = argv[1]
16-
csvPath = input("please enter the path to your CSV file: ")
17-
elif len(argv) >= 3:
18-
xmlPath = argv[1]
19-
csvPath = argv[2]
20+
21+
xmlPath, csvPath = getInputAndOutputFiles()
2022

2123
print("started to convert your file...")
2224

23-
# from line 29 to 33
25+
# from line 31 to 35
2426
# I read the file from the xmlPath variable, and got the dictory from parseXML
2527
# After that I got the first key from the dict (asumming the user passed a single xml liked the test.xml file)
2628
# After that I got the list of nodes inside the "root"
2729
# And finally I close the file
28-
29-
xmlFile = open(xmlPath, "r")
30-
data_dict = parseXML(xmlFile.read())
31-
data_root = data_dict[list(data_dict.keys())[0]]
32-
itemsList = list(data_root.values())[0]
33-
xmlFile.close()
34-
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()
3538
# Declared a csvWrite (object to write rows on a csv file)
3639
csvFile = open(csvPath, "w")
3740
csvWriter = CSVWriter(csvFile)
3841

3942

40-
# from line 46 to 53
43+
# from line 49 to 57
4144
# I iterated over all the items on the child of the file root
4245
# After that i made the variable item into a real dict so I could use
4346
# .keys and .values, the keys for the header row

0 commit comments

Comments
 (0)