<p><strong>从目录及其所有子目录获取完整文件路径</strong></p>
<pre><code>import os
def get_filepaths(directory):
"""
This function will generate the file names in a directory
tree by walking the tree either top-down or bottom-up. For each
directory in the tree rooted at directory top (including top itself),
it yields a 3-tuple (dirpath, dirnames, filenames).
"""
file_paths = [] # List which will store all of the full filepaths.
# Walk the tree.
for root, directories, files in os.walk(directory):
for filename in files:
# Join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath) # Add it to the list.
return file_paths # Self-explanatory.
# Run the above function and store its results in a variable.
full_file_paths = get_filepaths("/Users/johnny/Desktop/TEST")
</code></pre>
<hr/>
<ul>
<li>我在上面的函数中提供的路径包含3个文件-其中两个在根目录中,另一个在名为“subfolder”的子文件夹中</li>
<li><p>将打印列表的<code>print full_file_paths</code>:</p>
<ul>
<li><code>['/Users/johnny/Desktop/TEST/file1.txt', '/Users/johnny/Desktop/TEST/file2.txt', '/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat']</code></li>
</ul></li>
</ul>
<p>如果愿意,可以打开并读取内容,或者只关注扩展名为“.dat”的文件,如下面的代码所示:</p>
<pre><code>for f in full_file_paths:
if f.endswith(".dat"):
print f
</code></pre>
<p><code>/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat</code></p>