最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Python更新文件最后修改时间

Python crifan 491浏览 0评论
折腾:
【未解决】用Python从gitbook的markdown文件SUMMARY.md生成相关md文件
期间,用Python更新已存在的文件,把文件最后修改时间改为当前最新时间
python update file modified time
Change Date Modified for file after writing in Python – Stack Overflow
metadata – How to modify the file modification date with python on mac? – Stack Overflow
unix – How can I set the last modified time of a file from python? – Stack Overflow
import os

os.utime(path_to_file, (access_time, modification_time))
去试试
Python os.utime() Method – Tutorialspoint
Change File Modification Time In Python – Nitratine
os utime
Python os.utime() 方法 | 菜鸟教程 (runoob.com)
os — Miscellaneous operating system interfaces — Python 3.9.5 documentation
期间报错:
【未解决】Python中os.stat报错:TypeError not all arguments converted during string formatting
继续调试:
os.utime(filePath, (newAccessTime, newModificationTime))
的调试效果:
【总结】
最后用代码:
import os


    """Update file access time and modification time


    Args:
        filePath (str): file path
        newAccessTime (int): new file access time, float
        newModificationTime (int): new file modification time, float
        isAccessSameWithModif (bool): make access same with modification 
    Returns:
        None
    Raises:
    Examples:
        newModificationTime=1620549707.664307
    """
    if (not newAccessTime) and (not newModificationTime):
        return
    
    statInfo = os.stat(filePath)
    # print("statInfo=%s" % statInfo)
    # print("statInfo.st_info=%s" % statInfo.st_info)


    if not newAccessTime:
        oldAccessTime = statInfo.st_atime # 1619490904.6651974
        print("oldAccessTime=%s" % oldAccessTime)
        newAccessTime = oldAccessTime


    if not newModificationTime:
        oldModificationTime = statInfo.st_mtime # 1617002149.62217
        print("oldModificationTime=%s" % oldModificationTime)
        newModificationTime = oldModificationTime


    if isAccessSameWithModif:
        newAccessTime = newModificationTime


    os.utime(filePath, (newAccessTime, newModificationTime))
调用:
from datetime import datetime
...
                curDateTime = datetime.now() # datetime.datetime(2021, 5, 9, 16, 41, 9, 399425)
                curTimestamp = curDateTime.timestamp() # 1620549669.399425
                updateFileTime(mdAbsPath, newModificationTime=curTimestamp)
即可。

转载请注明:在路上 » 【已解决】Python更新文件最后修改时间

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
86 queries in 0.140 seconds, using 20.65MB memory