Python Get File Directory
Last Updated : Jul 1, 2023
IN - Python
In this article we will show you the solution of python get file directory, the purpose of this tutorial is to demonstrate how you can use Python to get the current directory and how to change the working directory.
Directories are nothing more than folders, and if you are new to programming, you may not know what they are.
A hierarchy of directories may appear inside a root folder, such as C:/ or D:/, with each directory containing files or subdirectories.
You can view a file's path by right-clicking the file and choosing Properties > General > Location in Windows; to retrieve a file in Python, you only need to know its exact path.
In the same way, when running a script, the working directory needs to be set to the directory where the script is located.
It is important to understand the Current Working Directory (CWD) when running multiple scripts or handling files. We will now discuss the idea of how to get a file directory in python with example.
Step By Step Guide On Python Get File Directory :-
import os # folder path dir_path = r'E:\\account\\' # list to store files res =  # Iterate directory for path in os.listdir(dir_path): # check if current path is a file if os.path.isfile(os.path.join(dir_path, path)): res.append(path) print(res)
- Python's os module provides functionalities such as reading and writing to the file system that are dependent on the operating system.
- Create a variable dir_path which contains the path to the folder we want to iterate over.
- Create an empty list res which will be used to store the names of files found in the dir_path folder.
- The os.listdir() function can be used to iterate over every path in the dir_path folder using a for loop.
- For each path, use the os.path.isfile() function to check if it is a file (as opposed to a subfolder).
- If the path is a file, use the os.path.join() function to join the dir_path and path together, then append the resulting file path to the res list.
- Print the res list which contains the names of all the files found in the dir_path folder.
As a result, we have successfully learned how to get file directory in python.
Absolute paths, on the other hand, allow you to determine the full path of a file or directory within the current working directory.
Having this flexibility gives you the ability to identify files or folders across different operating systems and return the correct path.
A Python program that gets an absolute path uses the os.path.abspath function.
By entering the file name, it will display the full path relative from the current working directory, including the file name.
I hope this article on python get file directory helps you and the steps and method mentioned above are easy to follow and implement.