How to create an empty file in Python? If the file already exists, make it empty.

I understand that you can use

open(file, "w").close() 

but it doesn't look very readable. Why to create open and close immediately? Are there any other options?

  • Weird question. You can not close the file if it is empty. Well, or you can still: from io import FileIO; FileIO(file, 'w') from io import FileIO; FileIO(file, 'w') - mkkik February
  • @mkkik I just need to create it, do not write anything there. Why can I not close the file? - bob
  • Because it is empty, you are not losing data. - mkkik

1 answer 1

By analogy with the touch utility:

 from pathlib import Path Path('/tmp/file').touch() 
  • Thank you, it looks better - bob
  • 2
    Only touch will not make the file empty if it already exists. - strawdog