简体   繁体   中英

Python Convert all csv files in folder to txt

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()

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM