utime() 在 Windows 中无效

utime() has no effect in Windows

我有一个 python 脚本,它应该遍历目录中的所有文件并将每个文件的日期设置为当前时间。它似乎没有效果,即文件资源管理器中的日期列没有显示任何变化。我看到代码循环遍历所有文件,似乎对 utime 的调用没有效果。

问题是 not this 因为大多数日期都是几个月前的。

# set file access time to current time
#!/usr/bin/python

import os
import math

import datetime

def convertSize(size):
    if (size == 0):
        return '0B'
    size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
    i = int(math.floor(math.log(size,1024)))
    p = math.pow(1024,i)
    s = round(size/p,2)
    return '%s %s' % (s,size_name[i])

# see www.tutorialspoint.com/python/os_utime.htm
def touch(fname, times=None):
    fhandle = open(fname, 'a')
    try:
        os.utime(fname, times)
    finally:
        fhandle.close()

def main():

    print ("*** Touch Files ***");

    aml_root_directory_string  = "C:\Documents"

    file_count = 0
    file_size = 0

    # traverse root directory, and list directories as dirs and files as files
    for root, dirs, files in os.walk(aml_root_directory_string):
        path = root.split('/')
        #print((len(path) - 1) * '---', os.path.basename(root))
        for file in files:
            filename, file_extension = os.path.splitext(file)
            print(len(path) * '---', file)
            touch(filename, )

#  
    print ("\n*** Total files: " + str(file_count) + "  Total file size: " + convertSize(file_size) + " ***");
    print ("*** Done: Time: " + str(datetime.datetime.now()) + "  - Touch Files ***");


# main ###############################################################################

if __name__ == "__main__":
    # stuff only to run when not called via 'import' here
    main()

编辑:
以防将来有人读到这篇文章,同样重要的是要注意文件浏览器可以 display more than 1 kind of date

os.utime 确实适用于 Windows,但您可能在资源管理器中查看了错误的日期。 os.utime 不修改创建日期(它看起来像是在资源管理器中的日期字段中使用的)。它确实更新了 "Date modified" 字段。如果您右键单击类别栏并选中 "date modified" 框,您可以看到这一点。或者启动命令行并键入 "dir"。此处显示的日期应反映更改。

我在 python 2.7 上测试了 os.utime,你必须给出两个参数:

os.utime("file.txt", None)

和 Python 3 其中第二个参数默认为 None:

os.utime("file.txt")

您遇到了三个问题:

  1. 您在 touching 时使用的是文件名,而不是完整路径,因此所有 touching 都发生在工作目录中
  2. 你也去掉了文件扩展名,所以触摸的文件没有扩展名
  3. 您正在触摸具有打开文件句柄的文件,在 Windows 和 Python 2.7 上,这是一个问题,因为 os.utime opens the files with no sharing allowed 不兼容使用现有的打开文件句柄

要修复 #3,请将您的 touch 方法更改为:

def touch(fname, times=None):
    # Open and immediately close file to force existence
    with open(fname, 'ab') as f:
        pass
    # Only alter times when file is closed
    os.utime(fname, times)

要修复#1 和#2,请将您的主要方法更改为调用 touch,如下所示:

            touch(os.path.join(root, file))

使用原始名称并将其与正在遍历的根目录连接起来,其中 touch(filename) 在程序的工作目录中接触了一个没有扩展名的文件(因为您使用了不合格的名称)。如果你找到程序的工作目录(print os.getcmd() 会告诉你去哪里找),你会在那里找到一堆随机的空文件,这些文件对应于你在遍历的树中找到的文件,去掉了路径和文件扩展名.

旁注:如果你可以移动到 Python 3(已经有一段时间了,并且有很多改进),你可以使更安全(无竞争)和更快 touch 感谢 os.utime:

中的文件描述符支持
def touch(fname, times=None):
    with open(fname, 'ab') as f:
        os.utime(f.fileno(), times)

并非所有系统都支持文件描述符,因此如果您需要处理此类系统,请根据 file descriptor support via os.supports_fd.

的测试定义 touch