如何在循环中动态创建目标文件名列表?

时间:2019-04-15 16:37:26

标签: python python-3.x

我正在尝试创建一个文件列表,这些文件中带有某个字符串的.csv格式,但我的列表仅存储所有文件名中的最后一个,尽管在循环中它会打印每个文件名。

我尝试创建一个列表,然后将其输出为csv,但是唯一输出的是列表的最后一个元素。

for fname in glob.glob('*.txt'):   
  if os.path.isfile(fname):    
    with open(fname) as f:   
        for line in f:       
            if 'target' in line:    
                mylist = []
                mylist.append(fname)
                #print ('found code in file %s' %fname)
                print(mylist)
                with open("out.csv","w") as l:
                    wr = csv.writer(l,delimiter="\n")
                    wr.writerow(mylist)
                    break

此代码的输出是

['target_1.txt']
['target_3.txt']

我希望这是csv格式,但是当我查看out.csv文件时,该文件中只有target_3.txt。 我想要的是带有行的csv:

['target_1.txt']
['target_3.txt']

2 个答案:

答案 0 :(得分:2)

以@JonClements评论并发布作为答案,以使其更容易理解他的意思。

with open("out.csv","w") as l:                # Open "out.csv" ONCE
    for fname in glob.glob('*.txt'):   
        if os.path.isfile(fname):    
            with open(fname) as f:   
                for line in f:       
                    if 'target' in line:    
                        mylist = []
                        mylist.append(fname)
                        #print ('found code in file %s' %fname)
                        print(mylist)
                        wr = csv.writer(l,delimiter="\n")
                        wr.writerows(mylist)
                        break

答案 1 :(得分:1)

注意缩进的区别。不必在with循环中执行第二个for,而是在相同的缩进级别上执行,即在完成循环之后。

mylist = []
for fname in glob.glob('*.txt'):
  if os.path.isfile(fname):
    with open(fname) as f:
        for line in f:
            if 'target' in line:
                mylist.append(fname)
                #print ('found code in file %s' %fname)
                break
with open("out.csv","w") as l:
    wr = csv.writer(l,delimiter="\n")
    wr.writerows(mylist)

还请注意我们如何在mylist循环之前创建for;您将在循环内覆盖该列表的先前值(也是如此)。如评论中所述,我也将writerow更改为writerows以写入所有收集的行。