How to Implement Touch using Python

To implement touch in Python, you can use the pathlib module’s “Path.touch()” method. It will create any file in any specified directory.

Syntax

Path.touch(mode=0o666, exist_ok=True)

Parameters

  1. mode: It suggests in which mode you want to create a file.
  2. exist_ok: If the file already exists, the function succeeds if the exist_ok argument is true (and its modification time is updated to the current time). Otherwise, FileExistsError is raised.

Import pathlib library

from pathlib import Path

Example: Touch a single file

Before touching a single file:

Empty directory before implementing touch

from pathlib import Path

Path("/Users/krunal/Desktop/code/pyt/database/file.txt").touch()

After touching a single file:

Output of implementing touch by creating a single file

That is it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.