简体   繁体   English

在 python 制作文件列表

[英]Making a file list in python

I don't know where's the problem.我不知道问题出在哪里。 Can you help me?你能帮助我吗?

main.py主程序

import os
from functions import *


if __name__ == "__main__":
    path = os.getenv('path')
    print(readFiles(path))
    

functions.py函数.py

import os

def readFiles(patha):
    res = []

    # Iterate directory
    currentpath = os.listdir(patha)
    
    for path in currentpath:
        # check if current path is a file
        if os.path.isfile(os.path.join(patha, path)):
            res.append(path)
        else:
            pathf = patha + path + '/'
            res.append(readFiles(pathf))


    return res

error错误

I wanted to make a file list in python and this error appeared.我想在python做一个文件列表出现这个错误。 No idea what went wrong.不知道出了什么问题。

Check your os.getenv('path') variable to make sure it is as expected.检查您的os.getenv('path')变量以确保它符合预期。 Also, I updated your code to make it work smoothly.另外,我更新了您的代码以使其顺利运行。

from pathlib import Path


def readFiles(patha):
    res = []
    print(patha)

    # Iterate directory
    currentpath = os.listdir(patha)

    for path in currentpath:
        # check if current path is a file
        try:
            f = os.path.join(patha, path)
            if os.path.isfile(f):
                res.append(f)
            elif os.path.isdir(f):
                res.extend(readFiles(f))
        except FileNotFoundError as e:
            print("warning,", e)

    return res


if __name__ == "__main__":
    path = Path.cwd()
    print(readFiles(path))

I suggest you to take a look at this question as well: How do I list all files of a directory?我建议你也看看这个问题: How do I list all files of a directory?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM