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

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

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


当前回答

看起来这是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。

其他回答

当关键字with已经发布时,此答案与Python-2.5以来的所有版本兼容。

1. 如果不存在则创建文件+设置当前时间 (与命令触摸完全相同)

import os

fname = 'directory/filename.txt'
with open(fname, 'a'):     # Create file if does not exist
    os.utime(fname, None)  # Set access/modified times to now
                           # May raise OSError if file does not exist

一个更健壮的版本:

import os

with open(fname, 'a'):
  try:                     # Whatever if file was already existing
    os.utime(fname, None)  # => Set current time anyway
  except OSError:
    pass  # File deleted between open() and os.utime() calls

2. 如果文件不存在,则创建该文件 (不更新时间)

with open(fname, 'a'):  # Create file if does not exist
    pass

3.只需更新文件访问/修改次数 (如果不存在,则不创建文件)

import os

try:
    os.utime(fname, None)  # Set access/modified times to now
except OSError:
    pass  # File does not exist (or no permission)

使用os.path.exists()不会简化代码:

from __future__ import (absolute_import, division, print_function)
import os

if os.path.exists(fname):
  try:
    os.utime(fname, None)  # Set access/modified times to now
  except OSError:
    pass  # File deleted between exists() and utime() calls
          # (or no permission)

奖励:更新目录中所有文件的时间

from __future__ import (absolute_import, division, print_function)
import os

number_of_files = 0

#   Current directory which is "walked through"
#   |     Directories in root
#   |     |  Files in root       Working directory
#   |     |  |                     |
for root, _, filenames in os.walk('.'):
  for fname in filenames:
    pathname = os.path.join(root, fname)
    try:
      os.utime(pathname, None)  # Set access/modified times to now
      number_of_files += 1
    except OSError as why:
      print('Cannot change time of %r because %r', pathname, why)

print('Changed time of %i files', number_of_files)

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

>>> from pathlib import Path
>>> Path('aa.txt').write_text("")
0
with open(file_name,'a') as f: 
    pass
def touch(fname):
    if os.path.exists(fname):
        os.utime(fname, None)
    else:
        open(fname, 'a').close()

这个方法试图比其他解决方案更无种族限制。(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)