简体   繁体   English

将多个文本文件转换为 csv

[英]convert multiple text files to csv

I have 3 text files in this example and would like to convert them to csv files : I can do it for one file but for multiple files i am aseeing errors after tweaking the code multiple times :在此示例中,我有 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()

In this particular case now i am running into problem because first i converted count to string and later i want to use it as integer in order to increment and check the condition.在这种特殊情况下,现在我遇到了问题,因为首先我将计数转换为字符串,后来我想将它用作整数以增加和检查条件。 Any other thoughts or way to do it or any suggestions to improve this way ?任何其他想法或方法或任何改进这种方式的建议?

The variable name you are using for the count of files, count =1 is also being used to loop through your file_name in for count in file_name: .您用于文件count =1的变量名称count =1也用于循环遍历您的 file_name in for count in file_name: Because of this, count will no longer be the current file number, but instead take on the characters of file_name .因此, count将不再是当前文件号,而是采用file_name的字符。

All you need to do is use a different variable name for your for loop.您需要做的就是为您的 for 循环使用不同的变量名称。 For example, for c in file_name:例如, for c in file_name:

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

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