Python 递归os.listdir?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19309667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Recursive os.listdir?
提问by tkbx
I'd like to get a list of all files in a directory recursively, with no directories.
我想递归地获取目录中所有文件的列表,没有目录。
Say there's a directory ~/files
with "a.txt", "b.txt", and a directory "c" with "d.txt" and "e" inside it, and "f.txt" inside e. How would I go about getting a list that looks like ['/home/user/files/a.txt', '/home/user/files/b.txt', '/home/user/files/c/d.txt', '/home/user/files/c/e/f.txt']
?
假设有一个~/files
包含“a.txt”、“b.txt”的目录,以及一个包含“d.txt”和“e”的目录“c”,以及其中包含“f.txt”的 e。我将如何获得一个看起来像的列表['/home/user/files/a.txt', '/home/user/files/b.txt', '/home/user/files/c/d.txt', '/home/user/files/c/e/f.txt']
?
回答by John La Rooy
import os
[os.path.join(dp, f) for dp, dn, fn in os.walk(os.path.expanduser("~/files")) for f in fn]