python - 如何修复仅添加到文件的列表中的一项
问题描述
我正在尝试创建一种方法,在其中扫描一堆文件夹并将它们的名称添加到列表中,然后取出文件名的特定位(数字)并将它们添加到.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!")
没有向我抛出错误消息,它不是第一个出现的项目,而是最后一个项目。我唯一的想法是每个项目都相互覆盖,如果是这种情况,我该如何改变呢?
解决方案
问题是,在每次迭代中,您都在覆盖您的文件。你应该改变这个:
# 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!")
推荐阅读
- css - 如何在没有导航栏的情况下增长 Bootstrap 元素以适应剩余高度?
- f# - 如何使用 F# SQLProvider 和 Postgres 快速获取相关数据?
- php - Laravel Eloquent - 无法使用数组获取列
- c# - 如何使用带有混淆代码的 ListViewItem.Text 属性
- java - 使用具有不同条件的 javax 验证来验证 Java 中对象的特定字段
- javascript - 悬停时图标的自定义动画
- javascript - Having troubles with synchronous rendering
- swift5 - AF 请求导致数据损坏“给定的数据不是有效的 JSON。” 迅速 5
- java - Java ArrayList<>() 的行为很奇怪
- javascript - 如何编辑 TextField 值,该值已预先定义