Archive

Archive for June, 2015

touch a file

Problem
In bash, the command “touch” creates an empty file (with size 0). How to do this in Python?

Solution
Simply open a file in write mode and write an empty string to it.

With the stdlib:

with open("empty.txt", "w") as f:
    f.write("")

With the excellent unipath library:

p = Path("empty.txt")
p.write_file("")

Note that this solution will overwrite your file if it exists. So be careful.

Categories: python Tags: ,