Python列表目录,子目录和文件 [英] Python list directory, subdirectory, and files
问题描述
我试图制作一个脚本来列出给定目录中的所有目录,子目录和文件。
我尝试过:
I'm trying to make a script to list all directory, subdirectory, and files in a given directory.
I tried this:
import sys,os
root = "/home/patate/directory/"
path = os.path.join(root, "targetdirectory")
for r,d,f in os.walk(path):
for file in f:
print os.path.join(root,file)
不幸的是它不能正常工作。
我得到所有的文件,但不是他们的完整的路径。
Unfortunatly it doesn't work properly.
I get all the files, but not their complete paths.
例如,如果dir结构将是:
For example if the dir struct would be:
/home/patate/directory/targetdirectory/123/456/789/file.txt
它将打印:
/home/patate/directory/targetdirectory/file.txt
什么我需要的是第一个结果。任何帮助将不胜感激!谢谢。
What I need is the first result. Any help would be greatly appreciated! Thanks.
推荐答案
使用 os.path.join
连接目录和文件名称:
for path, subdirs, files in os.walk(root):
for name in files:
print os.path.join(path, name)
注意在连接中使用路径
而不是根
,因为使用 root
将不正确。
Note the usage of path
and not root
in the concatenation, since using root
would be incorrect.
在Python 3.4中, pathlib 模块,以便更容易的路径操作。所以相当于 os.path.join
将是:
In Python 3.4, the pathlib module was added for easier path manipulations. So the equivalent to os.path.join
would be:
pathlib.PurePath(path, name)
pathlib
可以在路径上使用各种有用的方法。如果您使用具体的路径
变体,您还可以通过它们进行实际的操作系统调用,例如将目标调入目录,删除路径,打开指向的文件等等。
The advantage of pathlib
is that you can use a variety of useful methods on paths. If you use the concrete Path
variant you can also do actual OS calls through them, like chanding into a directory, deleting the path, opening the file it points to and much more.
这篇关于Python列表目录,子目录和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!