2016-02-01 64 views
2

我正在嘗試使用python更改windows系統的目錄創建時間戳。我有一個從另一個驅動器複製過來的目錄,並且不會保留目錄創建時間。這就是我希望做的,在Windows中使用python更改目錄創建時間(ctime)

第1步:閱讀源代碼目錄清單和thier用下面的代碼創建時間,

import os 
source_dir_path = r'd:\data' 
list_of_directories = os.listdir(source_dir_path) 
creation_times = {} 
for d in list_of_directories: 
    creation_times[d] = os.path.getctime(os.path.join(source_dir_path, d)) 

步驟2:遍歷目錄列表和設置目錄創建時間。爲此,我依靠Python For Windows Extensions。代碼如下所示,

from win32file import CreateFile, SetFileTime, GetFileTime, CloseHandle 
from win32file import GENERIC_READ, GENERIC_WRITE, OPEN_EXISTING 
from pywintypes import Time 

destination_dir_path = r'f:\data' 
#list_of_directories = os.listdir(source_dir_path) 
for d in creation_times: 
    fh = CreateFile(os.path.join(destination_dir_path,d), 0, 0, None, OPEN_EXISTING, 0,0) 
    SetFileTime(fh, creation_times[d]) 

我在CreateFile行收到'Access is Denied'。我不確定這是否是設置目錄創建時間的有效方法。這是正確的方式設置目錄創建時間

回答

0

下面的方法應該工作,雖然這也設置創建時間還爲最後訪問和最後寫入時間也。它創建文件名和創建時間的元組列表(而不是字典),將文件從源複製到目標目錄。您的代碼的主要問題是CreateFile呼叫所需的參數:

from win32file import CreateFile, SetFileTime, GetFileTime, CloseHandle 
from win32file import GENERIC_WRITE, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, FILE_SHARE_WRITE 

import os 
import shutil 

source_dir_path = r"c:\my_source" 
destination_dir_path = r"c:\my_target" 

creation_times = [(d, os.path.getctime(os.path.join(source_dir_path, d))) for d in os.listdir(source_dir_path)] 

for filename, ctime in creation_times: 
    src = os.path.join(source_dir_path, filename) 
    target = os.path.join(destination_dir_path, filename) 
    shutil.copy(src, target) 

    fh = CreateFile(target, GENERIC_WRITE, FILE_SHARE_WRITE, None, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0) 
    SetFileTime(fh, ctime, ctime, ctime)  
    CloseHandle(fh) 
+0

感謝Martin幫助您獲得正確的CreateFile調用。 – nitin