为给定文件夹生成文件名列表

2024-04-20 10:51:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我的问题是如何遍历文件夹并提取每个文件的路径信息。谢谢。你知道吗


Tags: 文件路径txt文件夹信息列表文件名document
1条回答
网友
1楼 · 发布于 2024-04-20 10:51:37

你可以试试这样的。你知道吗

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()

相关问题 更多 >