For 循环在写入输出文件时重复同一行

时间:2021-05-28 12:47:18

标签: python python-3.x

我有一个包含 295 个文本文件的文件夹,每个文件都包含几行我需要压缩的数据。我想打开一个文件,从该文件中提取两行,并将这两行合并到我创建的另一个文本文件中,然后关闭数据文件并重复下一个。

我目前有一个 for 循环,它主要执行此操作,但我遇到的问题是 for 循环复制了第一个实例的相同文本 295 次。我如何获得它以便它移动到文件列表中的下一个列表项?这是我的第一个 Python 程序,所以我很新。

我的代码:

import os

filelist = os.listdir('/colors')
colorlines = []

for x in filelist:
    with open('/colors/'+x, 'rt') as colorfile:         #opens single txt file for reading text as colorfile
        for colorline in colorfile:                     #Creates list from each line of the txt file and puts it into colorline
            colorlines.append(colorline.rstrip('\n'))   #removes the paragraph space in list
        tup = (colorlines[1], colorlines[3])            #combines second and fourth line into one line into a tuple
    str = ''.join(tup)                                  #joins the tuple into a string with no space between the two
    print(str)
    
    newtext = open("colorcode_rework.txt","a")          #opens output file for the reworked data
    newtext.write(str+'\n')                             #pastes the string and inserts a new line
    newtext.close()
    colorfile.close()

1 个答案:

答案 0 :(得分:0)

您需要为每个文件重新设置颜色行列表。当您调用列表中的特定项目(1 和 3)时,即使添加了更多项目,您也始终调用相同的项目。

要重置每个文件的颜色线列表:

for x in filelist:
  colorlines = []