2013-06-28 132 views
0

我有一個工作腳本,它將打印給定目錄中的所有文件。我想幫助它做兩件額外的事情:從目錄和子目錄中提取文件和時間戳

(1)也能夠打印每個文件的date_created或時間戳。 (2)以上所有內容不僅適用於給定目錄中的文件,而且也適用於所有子目錄。

這裏是工作的腳本:

from os import listdir 
from os.path import isfile, join 
from sys import argv 

script, filename = argv 

mypath = os.getcwd() 

allfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ] 

output = open(filename, 'w') 

for i in allfiles: 
    string = "%s" %i 
    output.write(string + "\n") 

output.close() 

print "Directory printed." 

我希望能夠打印出類似這樣(文件名+ 「」 +時間戳+ 「\ n」),或者一些替代品。

謝謝!

+0

(對於我目前的目的,只有打印時間戳就足夠了。) – user1893148

+0

真的,使用'os.walk'! –

回答

1

這個片段通過文件走在一個目錄下的子目錄+和打印出創建修改時間戳。

import os 
import time 

def walk_files(directory_path): 
    # Walk through files in directory_path, including subdirectories 
    for root, _, filenames in os.walk(directory_path): 
     for filename in filenames: 
      file_path = root + '/' + filename 
      created  = os.path.getctime(file_path) 
      modified = os.path.getmtime(file_path) 

      # Process stuff for the file here, for example... 
      print "File: %s" % file_path 
      print " Created:  %s" % time.ctime(created) 
      print " Last modified: %s" % time.ctime(modified) 


walk_files('/path/to/directory/') 
相關問題