【问题标题】:How do I add filenames to a list?如何将文件名添加到列表中?
【发布时间】:2020-01-14 15:37:10
【问题描述】:

我使用 for 循环创建了一系列 *.txt 文件。但现在我想把文件名写在一个列表中。但只有最后一个文件名被打印在列表中,而之前的文件名被删除。


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)

我得到的输出是 ['2.txt']
我需要输出为 ['0.txt', '1.txt', '2.txt']

【问题讨论】:

标签: python python-3.x list file loops


【解决方案1】:

您正在循环的每次迭代中重新初始化file_list。像这样把那部分移到外面:

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)

【讨论】:

    【解决方案2】:

    您在每次迭代中重新创建您的列表。 你应该在循环之前定义你的列表:

    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)
    

    【讨论】:

      【解决方案3】:

      在代码的第四行,您将 file_list 设置为一个空列表。由于这是在您的循环中,因此每次循环迭代时都会发生!如果您在 for 循环之前声明 file_list 变量并将其设置为起始空列表,您应该会得到预期的结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 2018-07-26
        相关资源
        最近更新 更多