python - 生成给定文件夹的文件名列表

标签 python python-3.x

文件夹中保存有文档列表,我需要将文件名及其路径保存在纯文本文件中,例如

/document/file1.txt
/document/file2.txt
...

我的问题是如何迭代文件夹并提取每个文件的路径信息。谢谢。

最佳答案

你可以尝试这样的事情。

import os
output_file = open(filename, 'w')
for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        f = print(os.path.join(root, name))
        output_file.write(f)
    for name in dirs:
        print(os.path.join(root, name))
output_file.close()

您还可以使用listdir()方法

file = open(filename, 'w')
    for f in os.listdir(dirName):
        f = os.path.join(dirName, f)
        file.write(f)
 file.close()

关于python - 生成给定文件夹的文件名列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43077996/

相关文章:

python - "virtualenv"中的库比系统库大得多

javascript - Django 中的 AJAX 渲染 JSON

python - Celery worker 不会为应用程序启动 ImportError

python - 函数调用作为在 python 3.x 中打印的参数

python - Discord Bot 无法离开语音 channel 'NoneType' 对象没有属性 'disconnect'

python - 如何以非阻塞的方式处理websocket数据?

Python Selenium StaleElementReferenceException : Message: stale element reference: element is not attached to the page document

python - 同名模块的两种实现-导入问题

python - 从 numpy 数组到 itk 图像

python - 用cap在python中积累