touch是一个Unix实用程序,它将文件的修改和访问时间设置为一天中的当前时间。如果该文件不存在,则使用默认权限创建该文件。
如何将其实现为Python函数?尽量跨平台和完整。
(目前谷歌的“python触摸文件”的结果不是很好,但指向os.utime。)
touch是一个Unix实用程序,它将文件的修改和访问时间设置为一天中的当前时间。如果该文件不存在,则使用默认权限创建该文件。
如何将其实现为Python函数?尽量跨平台和完整。
(目前谷歌的“python触摸文件”的结果不是很好,但指向os.utime。)
当前回答
我有一个用于备份的程序:https://stromberg.dnsalias.org/~strombrg/backshift/
我使用vmprof对它进行了分析,发现到目前为止,触摸是最耗时的部分。
所以我研究了快速接触文件的方法。
我发现在CPython 3.11上,这是最快的:
def touch3(filename, flags=os.O_CREAT | os.O_RDWR):
"""Touch a file using os.open+os.close - fastest on CPython 3.11."""
os.close(os.open(filename, flags, 0o644))
在Pypy3 7.3.9上,这是最快的:
def touch1(filename):
"""Touch a file using pathlib - fastest on pypy3, and fastest overall."""
Path(filename).touch()
在这两者中,pypy3的最佳性能仅略快于cpython的最佳性能。
我可能有一天会创建一个关于这个的网页,但现在我所拥有的只是一个Subversion repo: https://stromberg.dnsalias.org/svn/touch/trunk 它包括我尝试过的4种触摸方式。
其他回答
def touch(fname):
if os.path.exists(fname):
os.utime(fname, None)
else:
open(fname, 'a').close()
以下是充分的:
import os
def func(filename):
if os.path.exists(filename):
os.utime(filename)
else:
with open(filename,'a') as f:
pass
如果你想设置一个特定的触摸时间,使用操作系统。使用时间如下:
os.utime(filename,(atime,mtime))
这里,atime和mtime都应该是int/float,并且应该等于epoch time(以秒为单位)到你想设置的时间。
with open(file_name,'a') as f:
pass
复杂(可能有bug):
def utime(fname, atime=None, mtime=None)
if type(atime) is tuple:
atime, mtime = atime
if atime is None or mtime is None:
statinfo = os.stat(fname)
if atime is None:
atime = statinfo.st_atime
if mtime is None:
mtime = statinfo.st_mtime
os.utime(fname, (atime, mtime))
def touch(fname, atime=None, mtime=None):
if type(atime) is tuple:
atime, mtime = atime
open(fname, 'a').close()
utime(fname, atime, mtime)
这也尝试允许设置访问或修改时间,就像GNU touch。
你为什么不试试: newfile.py
#!/usr/bin/env python
import sys
inputfile = sys.argv[1]
with open(inputfile, 'r+') as file:
pass
Python newfile.py foobar.txt
or
使用子流程:
import subprocess
subprocess.call(["touch", "barfoo.txt"])