touch是一个Unix实用程序,它将文件的修改和访问时间设置为一天中的当前时间。如果该文件不存在,则使用默认权限创建该文件。
如何将其实现为Python函数?尽量跨平台和完整。
(目前谷歌的“python触摸文件”的结果不是很好,但指向os.utime。)
touch是一个Unix实用程序,它将文件的修改和访问时间设置为一天中的当前时间。如果该文件不存在,则使用默认权限创建该文件。
如何将其实现为Python函数?尽量跨平台和完整。
(目前谷歌的“python触摸文件”的结果不是很好,但指向os.utime。)
当前回答
你为什么不试试: 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"])
其他回答
这个方法试图比其他解决方案更无种族限制。(with关键字是Python 2.5中新增的。)
import os
def touch(fname, times=None):
with open(fname, 'a'):
os.utime(fname, times)
大致相当于这个。
import os
def touch(fname, times=None):
fhandle = open(fname, 'a')
try:
os.utime(fname, times)
finally:
fhandle.close()
现在,要真正使其无竞争,您需要使用futimes并更改打开文件句柄的时间戳,而不是打开文件然后更改文件名上的时间戳(可能已重命名)。不幸的是,Python似乎没有提供一种不通过ctypes或类似的方法来调用futimes…
EDIT
正如Nate Parsons所指出的,Python 3.3将为os.supports_fd等函数添加指定文件描述符(当os.supports_fd时)。Utime,它将使用futimes系统调用,而不是在底层使用utimes系统调用。换句话说:
import os
def touch(fname, mode=0o666, dir_fd=None, **kwargs):
flags = os.O_CREAT | os.O_APPEND
with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f:
os.utime(f.fileno() if os.utime in os.supports_fd else fname,
dir_fd=None if os.supports_fd else dir_fd, **kwargs)
复杂(可能有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。
简单的:
def touch(fname):
open(fname, 'a').close()
os.utime(fname, None)
打开确保那里有一个文件 utime确保时间戳被更新
从理论上讲,可能有人会在打开文件后删除该文件,导致utime引发异常。但可以说这没什么,因为坏事确实发生了。
为什么不试试呢?:
import os
def touch(fname):
try:
os.utime(fname, None)
except OSError:
open(fname, 'a').close()
我相信这消除了任何重要的竞争条件。如果文件不存在,则会抛出异常。
这里唯一可能的竞态条件是,文件是在调用open()之前,但在os.utime()之后创建的。但这并不重要,因为在这种情况下,修改时间将如预期的那样,因为它必须发生在调用touch()期间。
Write_text()从pathlib。路径可以使用。
>>> from pathlib import Path
>>> Path('aa.txt').write_text("")
0