Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Python

How to Implement Touch using Python

  • 28 Apr, 2025
  • Com 0
Python touch module

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

Name Value
mode It determines the way you want to create a file.
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.

Importing the pathlib library

from pathlib import Path

Touch a single file

Before touching a single file

Before touching a single file

from pathlib import Path

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

After touching a single file

After touching a single file

Creating multiple files using touch

We can create multiple files by using a loop and pathlib.Path.touch() method.

from pathlib import Path

# List of files you want to touch
file_list = [
    "parent/file1.txt",
    "parent/app.log",
    "parent/report.csv",
]

for file_path in file_list:
    path = Path(file_path)
    # Make sure parent directories exist
    if path.parent:
        path.parent.mkdir(parents=True, exist_ok=True)
    # Create file if missing, or update its modification time if present
    path.touch(exist_ok=True)

Creating multiple files using touch

That is it.

Post Views: 23
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

How to Create File If It Does Not Exist in Python
Printing a List of Files in Directory and Subdirectories in Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend