SoFunction
Updated on 2025-03-02

How to represent relative paths in python

The following path introduces the following path expression when opening a file in a py file written by Windows:

open('')
open('/data/')
open('D:\\user\\')

Among these three expressions, the first two are relative paths, and the third is absolute path. The absolute path is easier to understand, it is the most complete path, and the relative path is an incomplete path. This relative refers to the current folder path, which is actually the folder path placed in the py file you wrote! In other words, the relative path you write must be file a in the current folder A or file in folder B in A to open.

Assume that the current py folder is located at: D:\user\public

Then the paths to the file opened by the three lines of code are:

D:\user\public\

D:\user\public\data\

D:\user\private\

It is easy to understand that when you want to open the file where the py file is located, you just need to use the relative path, while if you want to use other folders, you need to use absolute paths.

Note: We often use '/' to represent relative paths, '\' to represent absolute paths. In the above path, \\ means escape. If you don't understand, you can use Baidu.

In addition, web page URLs and linux and unix systems are generally used '/'

Of course we can also get the absolute path to the current folder, as follows:

import os
path1=('.')   # indicates the absolute path to the folder you are currently inpath2=('..')  #Indicates the absolute path to the folder on the current folder

Therefore, we often set a path1 global variable to represent the current absolute path, and add a relative path to open the file that needs to be opened. This is done to avoid conflicts on different platforms, because there are differences in the representation of the relative paths on different platforms.

Knowledge point expansion:

1. Absolute path

 ("file name"):

It shows the absolute road power of a file

>>> import os

>>> ("E:\\PycharmProjects\\odycmdb\\odycmdb")

>>> ()

['', '', '', '__init__.py', '__pycache__']

>>> ("")

'E:\\PycharmProjects\\odycmdb\\odycmdb\\' 

2. Relative path

("file name"):

Shows the relative path of a file

>>> import os

>>> ("E:\\PycharmProjects\\odycmdb\\odycmdb")

>>> ()

['', '', '', '__init__.py', '__pycache__']

>>> ("")

This is the end of this article about how to represent relative paths in python. For more related python relative path writing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!