---
title: "Python 中列出目录中所有文件的方法"
author: "cloudhe"
date: "2008-08-15T14:17:16Z"
tags: []
slug: "python"
draft: false
lastmod: "2008-08-15T14:17:16Z"
id: 228365
url: "https://cloudhe.iteye.com/blog/228365"
---

```
import string, os, sys

dir = '/var'
print '----------- no sub dir'

files = os.listdir(dir)
for f in files:
    print dir + os.sep + f

print '----------- all dir'

for root, dirs, files in os.walk(dir):
    for name in files:
        print os.path.join(root, name)
```

   
前面的 os.listdir 可以列出 dir 里面的所有文件和目录，但不包括子目录中的内容。os.walk 可以遍历下面的所有目录，包括子目录。

 

from [http://www.pythonid.com/html/fenleiwenzhang/normalproblem/20070910/172.html](http://www.pythonid.com/html/fenleiwenzhang/normalproblem/20070910/172.html)