-1

I created a series of *.txt file using the for loop. But now I want to write the file names in a list. But only the last file name is getting printed in the list and the before ones gets deleted.


for i in range(3):
    i += 0
    new_file = str(i) + ".txt"
    file_list = []        
    file_list.append(new_file)

    with open(new_file, "w") as outfile:
        print("File created...")
print(file_list)

The output I am getting is ['2.txt']
I need the output to be ['0.txt', '1.txt', '2.txt']

Ethan
  • 77
  • 1
  • 9
  • 4
    Your declaring your list in the loop. This will delete the list every loop. Also, your incrementer is not doing anything – Joe Sep 12 '19 at 17:53
  • Possible duplicate of [Python For Loop Appending Only Last Value to List](https://stackoverflow.com/questions/53784325/python-for-loop-appending-only-last-value-to-list) – Fynn Becker Sep 12 '19 at 18:29

3 Answers3

2

You are re-initializing the file_list in each iteration of the loop. Move that part outside like so:

file_list = []        
for i in range(3):
    i += 0
    new_file = str(i) + ".txt"
    file_list.append(new_file)

    with open(new_file, "w") as outfile:
        print("File created...")
print(file_list)
rdas
  • 20,604
  • 6
  • 33
  • 46
1

You are recreating your list at each iteration. You should define your list before the loop:

file_list = []  
for i in range(3):
    i += 0
    new_file = str(i) + ".txt"      
    file_list.append(new_file)

    with open(new_file, "w") as outfile:
        print("File created...")
print(file_list)
Paulloed
  • 333
  • 1
  • 9
0

In the fourth line of your code, you're setting file_list equal to an empty list. Since this is in your loop, it's happening every time that the loop iterates! If you declare the file_list variable and set it to your starting empty list before your for loop, you should get your expected result.

Steve Archer
  • 641
  • 4
  • 10