简体   繁体   中英

How do I dynamically create a list of target filenames in a loop?

I am trying to create a list of files that have a certain string in them in a .csv format but my list only stores the last of all the filenames despite within the loop it prints each file name.

I have tried creating a list then outputting it as a csv but the only thing that is output is the last element of the list.

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

The output of this code is

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

I want this is csv form but when I look at the out.csv file there is only target_3.txt in the file. What I want is a csv with rows:

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

Taking @JonClements comments and posting as an answer to make it easier to understand what he's saying.

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

Notice the difference in indentation. Instead of doing the second with inside the for loop, do it at the same indentation level, ie after you have finished looping.

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)

Notice also how we create mylist before the for loop; you would overwrite the previous value of this list (too) inside the loop. As noted in a comment, I also changed writerow to writerows to write all the collected rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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