6 2-Filepath
6 2-Filepath
ipynb - Colab
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.
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)
path='example1.txt'
if os.path.exists(path):
print(f"The path '{path}' exists")
else:
print(f"The path '{path}' does not exists")
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.")
https://colab.research.google.com/drive/16ZGU__hd893nhg6hdhx7EC_EPgdBSaMD#printMode=true 1/2
7/18/24, 9:53 AM 6.2-filepath.ipynb - Colab
https://colab.research.google.com/drive/16ZGU__hd893nhg6hdhx7EC_EPgdBSaMD#printMode=true 2/2