touch是一个Unix实用程序,它将文件的修改和访问时间设置为一天中的当前时间。如果该文件不存在,则使用默认权限创建该文件。

如何将其实现为Python函数?尽量跨平台和完整。

(目前谷歌的“python触摸文件”的结果不是很好,但指向os.utime。)


当前回答

def touch(fname):
    if os.path.exists(fname):
        os.utime(fname, None)
    else:
        open(fname, 'a').close()

其他回答

还有一个用于触摸的python模块

>>> from touch import touch
>>> touch(file_name)

你可以用pip install touch安装它

简单的:

def touch(fname):
    open(fname, 'a').close()
    os.utime(fname, None)

打开确保那里有一个文件 utime确保时间戳被更新

从理论上讲,可能有人会在打开文件后删除该文件,导致utime引发异常。但可以说这没什么,因为坏事确实发生了。

Write_text()从pathlib。路径可以使用。

>>> from pathlib import Path
>>> Path('aa.txt').write_text("")
0
with open(file_name,'a') as f: 
    pass

对于更低级的解决方案,可以使用

os.close(os.open("file.txt", os.O_CREAT))