0

I have this code that converts my csv file into a txt version of an xml file.. How can I edit this to convert all files in a folder?

import csv

csvFile = 'path\to\input\123.csv'
xmlFile = 'path\to\output\123.txt'

csvData = csv.reader(open(csvFile))
xmlData = open(xmlFile, 'w')

rowNum = 0
for row in csvData:
    if rowNum == 0:
        tags = row
        # replace spaces w/ underscores in tag names
        for i in range(len(tags)):
            tags[i] = tags[i].replace(' ', '_')
    else: 
        xmlData.write('<products_joined>' + "\n")
        for i in range(len(tags)):
            xmlData.write('    ' + '<' + tags[i] + '><![CDATA[' \
                          + row[i] + ']]></' + tags[i] + '>' + "\n")
        xmlData.write('</products_joined>' + "\n")

    rowNum +=1

xmlData.close()
  • 1
    Possible duplicate of [Find all files in directory with extension .txt in Python](http://stackoverflow.com/questions/3964681/find-all-files-in-directory-with-extension-txt-in-python) – JazZ Aug 10 '16 at 20:33

2 Answers2

1

You can use glob:

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
    print(file)

Found here : Find all files in directory with extension .txt in Python

Community
  • 1
  • 1
JazZ
  • 4,469
  • 2
  • 20
  • 40
0

You could use glob to get all of the files in the folder then iterate over each of the files. You can make what you have a method then run the loop over the method and pass in the filename. https://docs.python.org/2/library/glob.html This gives an explanation of the glob function.

for file_path in Path('src').glob('**/*.c'):
    make_xml(file_path)
twothreebrent
  • 221
  • 3
  • 14