我如何在Python中获得给定目录中的所有文件(和目录)的列表?
当前回答
我知道这是一个老问题。如果你在linux机器上,这是我遇到的一种简洁的方法。
import subprocess
print(subprocess.check_output(["ls", "/"]).decode("utf8"))
其他回答
只递归列出文件的漂亮的一行代码。我在setup.py package_data指令中使用了这个:
import os
[os.path.join(x[0],y) for x in os.walk('<some_directory>') for y in x[2]]
我知道这不是问题的答案,但可能会派上用场
#import modules
import os
_CURRENT_DIR = '.'
def rec_tree_traverse(curr_dir, indent):
"recurcive function to traverse the directory"
#print "[traverse_tree]"
try :
dfList = [os.path.join(curr_dir, f_or_d) for f_or_d in os.listdir(curr_dir)]
except:
print "wrong path name/directory name"
return
for file_or_dir in dfList:
if os.path.isdir(file_or_dir):
#print "dir : ",
print indent, file_or_dir,"\\"
rec_tree_traverse(file_or_dir, indent*2)
if os.path.isfile(file_or_dir):
#print "file : ",
print indent, file_or_dir
#end if for loop
#end of traverse_tree()
def main():
base_dir = _CURRENT_DIR
rec_tree_traverse(base_dir," ")
raw_input("enter any key to exit....")
#end of main()
if __name__ == '__main__':
main()
这是一种遍历目录树中每个文件和目录的方法:
import os
for dirname, dirnames, filenames in os.walk('.'):
# print path to all subdirectories first.
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
# print path to all filenames.
for filename in filenames:
print(os.path.join(dirname, filename))
# Advanced usage:
# editing the 'dirnames' list will stop os.walk() from recursing into there.
if '.git' in dirnames:
# don't go into any .git directories.
dirnames.remove('.git')
下面是我经常使用的一个辅助函数:
import os
def listdir_fullpath(d):
return [os.path.join(d, f) for f in os.listdir(d)]
和我一起工作的是萨利赫在本页其他地方的回答的修改版本。
代码如下:
dir = 'given_directory_name'
filenames = [os.path.abspath(os.path.join(dir,i)) for i in os.listdir(dir)]