我的问题如下。我想列出目录及其子目录中的所有文件名,并将输出打印在 txt 文件中。现在这是我到目前为止的代码:
import os
for path, subdirs, files in os.walk('\Users\user\Desktop\Test_Py'):
for filename in files:
f = os.path.join(path, filename)
a = open("output.txt", "w")
a.write(str(f))
这会列出文件夹中的文件名(共有 6 个),但每个新文件都会覆盖旧文件,因此在任何给定时间,output.txt 文件中都只有一个文件名。如何更改此代码,以便将所有文件名写入 output.txt 文件中?
不要打开您的文件for
环形。在你之前打开它for
loop
像这样
import os
a = open("output.txt", "w")
for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'):
for filename in files:
f = os.path.join(path, filename)
a.write(str(f) + os.linesep)
或者使用上下文管理器(这是更好的做法):
import os
with open("output.txt", "w") as a:
for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'):
for filename in files:
f = os.path.join(path, filename)
a.write(str(f) + os.linesep)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)