2018년 7월 15일 일요일

[Python] Get File List in Folder


1. Get File List using os.listdir
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import os

def getFileList(folder):
    fileList = [ ]
    files = os.listdir(folder)
    for file in files:
        fullpath = os.path.join(folder,file)
        if os.path.isdir(fullpath):
            fileList = fileList + getFileList(fullpath)
        else:
            fileList.append(fullpath)
    return fileList

if __name__ == "__main__":
    files = getFileList("D:\Temp")
    for f in files:
        print(f)

Output:
D:\Temp\file1.txt
D:\Temp\file2.txt
D:\Temp\folder1\file3.txt
D:\Temp\folder1\file4.txt
D:\Temp\folder2\file5.txt
D:\Temp\folder2\file6.txt

2. Get File List using os.walk

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import os

def getFileListByWalk(folder):
    from os import walk
    f = []
    for (dirpath, dirnames, filenames) in walk(folder):
        for filename in filenames:
            f.append(os.path.join(dirpath,filename))
    return f

if __name__ == "__main__":
    files = getFileListByWalk("D:\Temp")  
    for f in files:
        print(f)  




댓글 없음:

댓글 쓰기