【问题标题】:Python Convert all csv files in folder to txtPython将文件夹中的所有csv文件转换为txt
【发布时间】:2016-12-17 09:34:24
【问题描述】:

我有这段代码可以将我的 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()

【问题讨论】:

标签: python python-2.7 python-3.4


【解决方案1】:

你可以使用glob:

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

在这里找到:Find all files in directory with extension .txt in Python

【讨论】:

    【解决方案2】:

    您可以使用 glob 获取文件夹中的所有文件,然后遍历每个文件。您可以制作您拥有的方法,然后在该方法上运行循环并传入文件名。 https://docs.python.org/2/library/glob.html 这给出了 glob 函数的解释。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多