使用 Python 实现触摸? [英] Implement touch using Python?

查看:106
本文介绍了使用 Python 实现触摸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

touch is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.

您将如何将其实现为 Python 函数?尝试跨平台和完整.

How would you implement it as a Python function? Try to be cross platform and complete.

(python touch 文件"的当前 Google 搜索结果不是很好,但指向 os.utime.)

(Current Google results for "python touch file" are not that great, but point to os.utime.)

推荐答案

看起来这是 Python 3.4 的新内容 - pathlib.

Looks like this is new as of Python 3.4 - pathlib.

from pathlib import Path

Path('path/to/file.txt').touch()

这将在路径上创建一个 file.txt.

This will create a file.txt at the path.

--

Path.touch(mode=0o777,exist_ok=True)

Path.touch(mode=0o777, exist_ok=True)

在此给定路径创建一个文件.如果给出了 mode,它会与进程的 umask 值结合来确定文件模式和访问标志.如果文件已经存在,则如果exist_ok 为true(并且其修改时间更新为当前时间),则该函数成功,否则引发FileExistsError.

Create a file at this given path. If mode is given, it is combined with the process’ umask value to determine the file mode and access flags. If the file already exists, the function succeeds if exist_ok is true (and its modification time is updated to the current time), otherwise FileExistsError is raised.

这篇关于使用 Python 实现触摸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆