Dillon Lloyd
Dillon Lloyd

Reputation: 125

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']

Upvotes: 0

Views: 437

Answers (2)

Nick Vitha
Nick Vitha

Reputation: 476

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

Upvotes: 2

tripleee
tripleee

Reputation: 189397

Notice the difference in indentation. Instead of doing the second with inside the for loop, do it at the same indentation level, i.e. 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.

Upvotes: 1

Related Questions