首页 > 解决方案 > 如何修复仅添加到文件的列表中的一项

问题描述

我正在尝试创建一种方法,在其中扫描一堆文件夹并将它们的名称添加到列表中,然后取出文件名的特定位(数字)并将它们添加到.txt文件中。

我目前已经到了一个阶段,我有一个完整的文件夹名称列表,我可以从字符串中提取数字。但是,将它们添加到.txt文件中似乎是一个问题。它只添加一项。

    def generateSetFile(self, path=None):
        if not path:
            print("Missing required argument: 'filename'")
        folders = []
        # iterating through path
        for r, d, f in os.walk(path): # where R=ROOT, D=DIRECTORIES,F=FILES
            for folder in d:
                folders.append(os.path.join(r, folder))

        print(folders) # definitely returns more than one index

        # adding all songnames to a txt file
        for f in folders:
            songname = f.split(" ")[0].split("\\") # getting numbers
            with open("mysongs.txt", "w+") as fp:
                fp.write(f"{songname[1]}\n") # newline for next item
        print("Done!")

没有向我抛出错误消息,它不是第一个出现的项目,而是最后一个项目。我唯一的想法是每个项目都相互覆盖,如果是这种情况,我该如何改变呢?

标签: pythonlistpython-requestsoperating-system

解决方案


问题是,在每次迭代中,您都在覆盖您的文件。你应该改变这个:

# adding all songnames to a txt file
    for f in folders:
        songname = f.split(" ")[0].split("\\") # getting numbers
        with open("mysongs.txt", "w+") as fp:
            fp.write(f"{songname[1]}\n") # newline for next item
    print("Done!")

这样:

# adding all songnames to a txt file
with open("mysongs.txt", "w+") as fp:
    for f in folders:
        songname = f.split(" ")[0].split("\\") # getting numbers
        fp.write(f"{songname[1]}\n") # newline for next item
print("Done!")

推荐阅读