touch是一个Unix实用程序,它将文件的修改和访问时间设置为一天中的当前时间。如果该文件不存在,则使用默认权限创建该文件。
如何将其实现为Python函数?尽量跨平台和完整。
(目前谷歌的“python触摸文件”的结果不是很好,但指向os.utime。)
touch是一个Unix实用程序,它将文件的修改和访问时间设置为一天中的当前时间。如果该文件不存在,则使用默认权限创建该文件。
如何将其实现为Python函数?尽量跨平台和完整。
(目前谷歌的“python触摸文件”的结果不是很好,但指向os.utime。)
当前回答
def touch(fname):
if os.path.exists(fname):
os.utime(fname, None)
else:
open(fname, 'a').close()
其他回答
with open(file_name,'a') as f:
pass
看起来这是Python 3.4的新功能- pathlib。
from pathlib import Path
Path('path/to/file.txt').touch()
这将在该路径下创建一个file.txt文件。
--
路径。触摸(模式= 0 o777 exist_ok = True) 在这个给定的路径上创建一个文件。如果给出了mode,它将与进程的umask值相结合,以确定文件模式和访问标志。如果文件已经存在,则如果exist_ok为true(并且其修改时间更新为当前时间),则函数成功,否则将引发FileExistsError。
还有一个用于触摸的python模块
>>> from touch import touch
>>> touch(file_name)
你可以用pip install touch安装它
以下是充分的:
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(以秒为单位)到你想设置的时间。
你为什么不试试: 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"])