2018年7月6日 星期五

[ Python 常見問題 ] Create empty file using python

Source From Here 
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: 
  1. open(x, 'a').close()  
Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either. In case you want touch's behaviour (i.e. update the mtime in case the file exists): 
  1. import os  
  2. def touch(path):  
  3.     with open(path, 'a'):  
  4.         os.utime(path, None)  
You could extend this to also create any directories in the path that do not exist: 
  1. basedir = os.path.dirname(path)  
  2. if not os.path.exists(basedir):  
  3.     os.makedirs(basedir)  
Supplement 
FAQ - Implement touch using Python? 

沒有留言:

張貼留言

[ Python 常見問題 ] How to shift a datetime object by 12 hours in python

Source From   Here   Question   Datetime   objects hurt my head for some reason. I am writing to figure out   how to shift a date time obje...