简体   繁体   中英

How do I add filenames to a list?

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
I need the output to be

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)

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)

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.

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