[英]How can I get all filename in different directories?
Lets say the directories hierarchy looks like this: 可以说目录层次结构如下所示:
A(root)
|
B---------C--------D
| | |
fileB.h fileC.png fileD.py
fileC1.jpg
E
|
fileE.py
How can I access all the doc? 如何访问所有文档? Or just get the path. 或者只是获得路径。 Is there a way to iterlate all? 有没有办法迭代所有?
What I do: 我所做的:
path = sys.path[0]
for filename_dir in os.listdir(path):
filename, ext = os.path.splitext(filename_dir)
if ext == '.h':
#do something
elif ext == '.png'
#do something
.....
But as I know listdir
can only access the directory where my program's py file located. 但是据我所知listdir
只能访问程序的py文件所在的目录。
This gives only the dirs and files under a directory, but not recursively: 这仅给出目录下的目录和文件,但不递归:
import os
for filename in os.listdir(path):
print filename
If you want to list absolute paths: 如果要列出绝对路径:
import os
def listdir_fullpath(d):
return [os.path.join(d, f) for f in os.listdir(d)]
If you want resursive search, this gives you an iterator that returns 3-tuples including the parent directory, list of directories, and list of files at each iteration: 如果要进行递归搜索,则可以使用迭代器在每次迭代时返回3元组,包括父目录,目录列表和文件列表:
for i,j,k in os.walk('.'):
print i, j, k
For example: 例如:
import os
path = sys.path[0]
for dirname, dirnames, filenames in os.walk(path):
for subdirname in dirnames:
print "FOUND DIRECTORY: ", os.path.join(dirname, subdirname)
for filename in filenames:
print "FOUND FILE: ", os.path.join(dirname, filename)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.