How to get file path + file name into a list?

This question already has an answer here:

  • How do I list all files of a directory? 31 answers

  • Since you have access to the directory path you could just do:

    dir = "train_dataham"
    output = map(lambda p: os.path.join(dir, p), os.listdir(dir))
    

    or simpler

    output = [os.path.join(dir, p) for p in os.listdir(dir)]
    

    Where os.path.join will join your directory path with the filenames inside it.


    If you're on Python 3.5 or higher, skip os.listdir in favor of os.scandir , which is both more efficient and does the work for you ( path is an attribute of the result objects):

    hamFileNames = [entry.path for entry in os.scandir(r"train_dataham")]
    

    This also lets you cheaply filter ( scandir includes some file info for free, without stat -ing the file), eg to keep only files (no directories or special file-system objects):

    hamFileNames = [entry.path for entry in os.scandir(r"train_dataham") if entry.is_file()]
    

    If you're on 3.4 or below, you may want to look at the PyPI scandir module (which provides the same API on earlier Python).

    Also note: I used a raw string for the path; while h happens to work without it, you should always use raw strings for Windows path literals, or you'll get a nasty shock when you try to use "train_datafoo" (where f is the ASCII form feed character), while r"train_datafoo" works just fine (because the r prefix prevents backslash interpolation of anything but the quote character).

    链接地址: http://www.djcxy.com/p/20056.html

    上一篇: Flask从服务器中选择文件

    下一篇: 如何获取文件路径+文件名到列表中?