In Python, accessing files using relative paths is a common practice, especially when dealing with files that are in the same directory or nearby as the script. The relative path is based on the current working directory (CWD, Current Working Directory), that is, the directory where the Python script is executed.
1. Current directory
When you see the ./ prefix in the file path, it represents the current directory. But in most operating systems and Python environments, it can be simply omitted./
, because if no path prefix is specified, Python will look for files in the current directory by default.
with open('', 'r') as file: # is equivalent to open('./', 'r') content = ()
2. Previous level directory
When you want to access files located in the previous directory of the current directory, you can use../
As a prefix for the path.
with open('../parent_directory/', 'r') as file: content = ()
3.Advanced Directory
You can continue with the above mode by adding more../
to access higher-level directories.
with open('../../grandparent_directory/', 'r') as file: content = ()
Notice: In the standard file path representation, there is no.../
This way of writing.
This is the article about how to use (.) to access files in python relative paths. For more related python relative paths, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!