如何更改Windows文件的创建日期?
我该如何通过Python来修改Windows文件的创建日期呢?
12 个回答
11
我的简单的filedate
模块可能正好符合你的需求。
优点:
- 界面非常简单
- 不依赖于特定平台
- 支持漂亮的字符串日期
- 日期持有者工具
安装
pip install filedate
使用方法
import filedate
Path = "~/Documents/File.txt"
filedate.File(Path).set(
created = "1st February 2003, 12:30",
modified = "3:00 PM, 04 May 2009",
accessed = "08/07/2014 18:30:45"
)
42
我不想为了设置文件的创建时间而引入整个 pywin32
/ win32file
库,所以我制作了一个叫做 win32-setctime
的小工具,它专门用来做这个事情。
pip install win32-setctime
然后你可以这样使用它:
from win32_setctime import setctime
setctime("my_file.txt", 1561675987.509)
其实,这个功能可以简化成几行代码,不需要其他任何依赖,只需要用到内置的 ctypes
Python 库:
from ctypes import windll, wintypes, byref
# Arbitrary example of a file and a date
filepath = "my_file.txt"
epoch = 1561675987.509
# Convert Unix timestamp to Windows FileTime using some magic numbers
# See documentation: https://support.microsoft.com/en-us/help/167296
timestamp = int((epoch * 10000000) + 116444736000000000)
ctime = wintypes.FILETIME(timestamp & 0xFFFFFFFF, timestamp >> 32)
# Call Win32 API to modify the file creation date
handle = windll.kernel32.CreateFileW(filepath, 256, 0, None, 3, 128, None)
windll.kernel32.SetFileTime(handle, byref(ctime), None, None)
windll.kernel32.CloseHandle(handle)
如果你想要更高级的管理(比如错误处理),可以查看 这个 win32_setctime.py
的源代码。
44
“剃 yak”这个说法真是太棒了。
import pywintypes, win32file, win32con
def changeFileCreationTime(fname, newtime):
wintime = pywintypes.Time(newtime)
winfile = win32file.CreateFile(
fname, win32con.GENERIC_WRITE,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
None, win32con.OPEN_EXISTING,
win32con.FILE_ATTRIBUTE_NORMAL, None)
win32file.SetFileTime(winfile, wintime, None, None)
winfile.close()