Python  

Python - File Path Handling Methods

In the last session, we discussed the Advanced functions methods and Operations. Now, we will look at Python's File Path Handling Methods.

Let’s start,

Handling file paths properly is essential when working with files in Python, ensuring your code runs smoothly across different operating systems and environments. Python offers various modules and functions that make it easier to manage and manipulate file paths reliably.

  1. Using the OS module

#Input
import os
cwd=os.getcwd()
print(f"Current working directory is {cwd}")

#Output
Current working directory is C:\Users\sriganapathi\python_file
  1. create a new directory in python methods

#Input
new_directory="package"
os.mkdir(new_directory)
print(f"Directory '{new_directory}' create")

#Output
Directory 'package' create
  1. Listing Files And Directories in current folder

#Input
items=os.listdir('.')
print(items)

#Output
['.ipynb_checkpoints', 'filepath.ipynb', 'package']
  1. Joining Paths method in python

#Input
dir_name="folder"
file_name="file.txt"
full_path=os.path.join(dir_name,file_name)
print(full_path)

#Output
folder\file.txt
  1. Joining Paths method and working directory

#Input
dir_name="folder"
file_name="file.txt"
full_path=os.path.join(os.getcwd(),dir_name,file_name)
print(full_path)

#Output
C:\Users\sriganapathi\folder\file.txt
  1. Checking the file is Present or Not

#Input
path='example1.txt'
if os.path.exists(path):
    print(f"The path '{path}' exists")
else:
    print(f"The path '{path}' does not exists")

#Output
The path 'example1.txt' does not exists
  1. Getting the absolute path in python

#Input
relative_path='example.txt'
absolute_path=os.path.abspath(relative_path)
print(absolute_path)

#Output
C:\Users\sriganapathi\example.txt
  1. Getting file name, extension, and parent folder in python

#Input
from pathlib import Path

p = Path(r"C:\Users\sriganapathi\filepath.ipynb")

print(p.name)       
print(p.stem)       
print(p.suffix)     
print(p.parent)     

#Output
filepath.ipynb
filepath
.ipynb
C:\Users\sriganapathi\

Now, We have covered file path operations with various examples. In the next article, we will dive into file operations in Python.