Home > python > touch a file

touch a file

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

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

With the stdlib:

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

With the excellent unipath library:

p = Path("empty.txt")

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

Categories: python Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: