如何在Python中获取目录下所有文件的列表。
我正在使用Notepad++的Python插件,想要打印出一个文件夹里所有文件的列表。简单来说,我需要运行类似于命令提示符里的“dir”命令。
有没有什么办法可以做到这一点呢?
2 个回答
1
下面是如何把一个文件夹及其所有子文件夹里的文件都放到一个列表里,并把这个列表打印出来的方法。
注意:关于如何“遍历”文件夹的内容,可以参考这里:
# Task: Get a printout of all the files in a directory.
import os
# The directory that we are interested in
myPath = "/users/george/documents/"
# All the file paths will be stored in this list
filesList= []
for path, subdirs, files in os.walk(myPath):
for name in files:
filesList.append(os.path.join(path, name))
for i in filesList:
print (str(i))
2
你可以使用 os.listdir()
这个函数来获取一个文件夹里所有文件的列表。