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? 

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...