Python:将一个目录及其子目录下的所有文件名写入一个文本文件

标签 python python-2.7

我的问题如下。我想列出我的目录及其子目录中的所有文件名,并将该输出打印在一个 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 循环之前打开它

像这样

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) 

关于Python:将一个目录及其子目录下的所有文件名写入一个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12199120/

相关文章:

Python 3 多进程分散器 : BrokenPipeError (Broken pipe)

python - 导入错误: Could not import settings 'mysite.settings' (Is it on sys.路径?): No module named mysite.设置

python - Paramiko - 使用私钥连接 - 不是有效的 OPENSSH 私钥/公钥文件

Python 2.7 将于 2020 年 1 月 1 日结束其生命周期

python - 是否有用于从 Python 访问 HBase 的好库?

python - 我想附加到一个新列表,仅添加第三个元素与第一个元组的第三个元素相同的元组

python-2.7 - Python 错误名称 'runfile' 未在 Spyder 中定义

python - 如何规范 CSV 中的字典?

python - 如何查看代码中某处悬停在其上的常量的值? [Pycharm集成开发环境]

python - 使用 Visual Studio 2015 安装 python 包时出错