Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python create empty file - Unix

I want to create empty file using Python script in Unix environment. Could see different ways mentioned of achieving the same. What are the benefits/pitfalls of one over the other.

os.system('touch abc')

open('abc','a').close()

open('abc','a')

subprocess.call(['touch','abc'])
like image 442
garg10may Avatar asked Apr 07 '26 02:04

garg10may


1 Answers

Well, for a start, the ones that rely on touch are not portable. They won't work under standard Windows, for example, without the installation of CygWin, GNUWin32, or some other package providing a touch utility..

They also involve the creation of a separate process for doing the work, something that's totally unnecessary in this case.

Of the four, I would probably use open('abc','a').close() if the intent is to try and just create the file if it doesn't exist. In my opinion, that makes the intent clear.

But, if you're trying to create an empty file, I'd probably be using the w write mode rather than the a append mode.

In addition, you probably also want to catch the exception if, for example, you cannot actually create the file.

like image 95
paxdiablo Avatar answered Apr 09 '26 16:04

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!