【发布时间】:2020-09-11 15:35:13
【问题描述】:
我是 python 的绝对初学者。我想在 files.txt 文件中的一个文件夹(pythonscript 所在的文件夹)中写入每个文件。当我只使用 for 循环运行脚本时,一切正常,我看到了文件夹的每个文件。当我插入 file() 函数将其写入文件时,我只得到文本文件中的最后一个文件夹。 mz问题出在哪里?
def dir_list():
for root, dirs, files in os.walk(".", topdown=False):
for name in dirs:
print(name)
dir_list()
工作正常并打印文件。
现在使用文件():
def dir_list():
for root, dirs, files in os.walk(".", topdown=False):
for name in dirs:
file = open("files.txt", "w")
file.write(name + "\n")
file.close()
dirlist()
我希望你能帮助我。 谢谢。
【问题讨论】:
-
您正在打开文件进行写入,因此每次都将其截断。您需要在循环之前使用
with语句打开它一次
标签: python-3.x os.walk