0% found this document useful (0 votes)
21 views2 pages

6 2-Filepath

Uploaded by

AB
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views2 pages

6 2-Filepath

Uploaded by

AB
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

7/18/24, 9:53 AM 6.2-filepath.

ipynb - Colab

keyboard_arrow_down Working With File Paths

When working with files in Python, handling file paths correctly is crucial to ensure your code works across different operating systems and
environments. Python provides several modules and functions for working with file paths effectively.

#### Using the os module


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

Current working directory is e:\UDemy Final\python\6-File Handling

## create a new directory


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

Directory 'package' create

## Listing Files And Directories


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

['6.1-fileoperation.ipynb', '6.2-filepath.ipynb', 'destination.txt', 'example.bin', 'example.txt', 'package']

### Joining Paths

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

folder\file.txt

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

e:\UDemy Final\python\6-File Handling\folder\file.txt

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

The path 'example1.txt' does not exists

#Checking if a Path is a File or Directory


import os

path = 'example.txt'
if os.path.isfile(path):
print(f"The path '{path}' is a file.")
elif os.path.isdir(path):
print(f"The path '{path}' is a directory.")
else:
print(f"The path '{path}' is neither a file nor a directory.")

The path 'example.txt' is a file.

## Getting the absolute path


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

https://colab.research.google.com/drive/16ZGU__hd893nhg6hdhx7EC_EPgdBSaMD#printMode=true 1/2
7/18/24, 9:53 AM 6.2-filepath.ipynb - Colab

e:\UDemy Final\python\6-File Handling\example.txt

Start coding or generate with AI.

https://colab.research.google.com/drive/16ZGU__hd893nhg6hdhx7EC_EPgdBSaMD#printMode=true 2/2

You might also like