【发布时间】:2019-03-16 12:10:29
【问题描述】:
import os
exts = ['ppt', 'pptx', 'doc', 'docx', 'txt', 'pdf', 'epub']
files = []
for root, dirnames, filenames in os.walk('.'):
for i in exts:
for file in filenames:
if file.endswith(i):
file1 = os.path.join(root, file)
print(file1)
with open(os.getcwd()+ r"\ally_"+i+".txt", 'w+') as f:
f.write("%s\n" % file1)
我正在尝试这段代码。如何使用 ex 写入系统中的所有文件。 doc 扩展为我桌面中名为 all_docs.txt 的文件? for 循环中的 file.write() 仅将每个扩展名的最后一行写入文件。
【问题讨论】:
-
请重新格式化您的代码
-
究竟是什么不起作用?有什么问题吗?
-
ally_doc.txt 文件中的输出仅包含 1 个文件名。但我希望我系统中的.doc 扩展名的所有文件都写入 ally_doc.txt。我应该如何解决这个问题?
-
我认为您需要以“a”(附加)模式打开文件
-
是的。 “a”模式有效!!非常感谢:)
标签: python file-handling os.walk