将多个文本文件转换为csv

问题描述 投票:-1回答:1

我在这个例子中有3个文本文件,并希望将它们转换为csv文件:我可以为一个文件执行但是对于多个文件我在多次调整代码后发现错误:

    import os
    import glob3


count =1
file_name = "COUNT16_DISTRIBUTION" + str(count*1) + ".txt"

def data_parser(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i,j)
    return text

while count<=3:
    for count in file_name:
        inputfile = open(file_name)
        outputfile = open("COUNT16_DISTRIBUTION" + str(count*1)+ '.csv', 'w')
        reps = {'"DUT 1"':' ', ' ':' ', ' ':' ' }
        for i in range(7):  inputfile.next()

        count = count + 1
        file_name = "COUNT16_DISTRIBUTION" + str(count * 1) + ".txt"
        for line in inputfile:
            outputfile.writelines(data_parser(line, reps))
    inputfile.close()
    outputfile.close()

在这种特殊情况下,我现在遇到了问题,因为首先我将count转换为字符串,后来我想将它用作整数,以便递增并检查条件。有任何其他想法或方法,或任何改善这种方式的建议?

python csv text
1个回答
0
投票

您用于文件计数的变量名称,count =1也用于循环遍历for count in file_name:中的file_name。因此,count将不再是当前的文件编号,而是采用file_name的字符。

您需要做的就是为for循环使用不同的变量名称。例如,for c in file_name:

© www.soinside.com 2019 - 2024. All rights reserved.