Question
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. How would you implement it as a Python function to create empty file or touch it if exist?
How-To
There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file. So the easiest way to simply create a file without truncating it in case it exists is this:
- open(x, 'a').close()
- import os
- def touch(path):
- with open(path, 'a'):
- os.utime(path, None)
- basedir = os.path.dirname(path)
- if not os.path.exists(basedir):
- os.makedirs(basedir)
* FAQ - Implement touch using Python?
沒有留言:
張貼留言