遍历python中的目录

时间:2014-11-13 17:09:31

标签: python

我正试图横穿目录并计算我正在进行,所以在结束程序输出将如下:

output:
 ./file last accessed 1/1/2000 # just sample date


./dirA has 1 file and 1 sub-dir
./dirA/test/ has 5 files

以下是代码,但我现在没有想法了:

directories = [startDir]
#!/usr/bin/python
import os,os.path, time


startDir = os.getcwd()
fileCount=0
directoryCount=0

while len(directories)>0:
directory = directories.pop()
for name in os.listdir(directory):
     fullpath = os.path.join(directory,name)
     lastAccess = os.stat(fullpath).st_atime
     accessTime = time.asctime(time.gmtime(lastAccess))
     if os.path.isfile(fullpath):
         print fullpath +" is file"+" "+ accessTime  
         fileCount+=1
     elif os.path.isdir(fullpath):
         directories.append(fullpath)
         directoryCount+=1
         print fullpath + " "+ accessTime

print fileCount, directoryCount # only test printing for now

这就是我现在所处的位置。为了防止我不清楚,我想列出当前目录(和子目录)中的文件以及它们上次访问的时间。我还想列出包含多少个文件和子目录的目录。

1 个答案:

答案 0 :(得分:0)

使用os.walk的提示:

for x,y,z in os.walk('your_path'):
...     for file in z:
...         print fullpath + ": "+ str(time.asctime(time.gmtime(os.stat(fullpath).st_atime)))

os.walk给出三个元组dir,subdir,files