6

Python を使用して Windows システムのディレクトリ作成タイムスタンプを変更しようとしています。別のドライブからコピーされたディレクトリがあり、ディレクトリの作成時刻が保持されません。これが私が望んでいることです。

ステップ 1 : 次のコードを使用して、ソース ディレクトリ リストとその作成時間を読み取ります。

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 行で「アクセスが拒否されました」というメッセージが表示されます。これがディレクトリの作成時間を設定する有効な方法かどうかはわかりません。これはディレクトリ作成時間を設定する正しい方法ですか

4

1 に答える 1

3

The following approach should work, although this does set the creation time also for the last access and last write times also. It creates a list of tuples (rather than a dictionary) of the filenames and creation times, copies the files from the source to the target directory. The main issue your code had was the parameters needed for the CreateFile call:

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)
于 2016-02-01T07:14:46.147 に答える