Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python For循环在写入输出文件时重复同一行_Python_Python 3.x - Fatal编程技术网

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

Python For循环在写入输出文件时重复同一行,python,python-3.x,Python,Python 3.x,我有一个包含295个文本文件的文件夹,每个文件包含两行需要压缩的数据。我想打开一个文件,从该文件中获取两行,然后将这两行合并到我创建的另一个文本文件中,然后关闭数据文件并重复下一个 我目前有一个for循环,它主要是这样做的,但我遇到的问题是for循环将第一个实例的相同文本复制295次。如何获取它,使其移动到文件列表中的下一个列表项?这是我用Python编写的第一个程序,所以我还是个新手 我的代码: import os filelist = os.listdir('/colors') color

我有一个包含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和3)中的特定项时,即使添加了更多项,也始终调用相同的项

要重置每个文件的颜色线列表,请执行以下操作:

for x in filelist:
  colorlines = []
您正在将所有文件附加到相同的
颜色线
列表中,但始终使用相同的两个元素:
颜色线[1],颜色线[3]
,它们是第一个文件的。。。只需将
colorlines=[]
移动到环路内,请阅读。您还可以使用它来帮助逐步可视化代码的执行。