简体   繁体   English

Python将文件夹中的所有csv文件转换为txt

[英]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? 我有将我的csv文件转换为xml文件的txt版本的代码。如何编辑此代码以转换文件夹中的所有文件?

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 : 您可以使用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 在这里找到: 在Python中以扩展名.txt查找目录中的所有文件

You could use glob to get all of the files in the folder then iterate over each of the files. 您可以使用glob获取文件夹中的所有文件,然后遍历每个文件。 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. https://docs.python.org/2/library/glob.html这给出了glob函数的解释。

for file_path in Path('src').glob('**/*.c'):
    make_xml(file_path)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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