Manipulation of file names and paths in Python

As mentioned in "Reading Files in Python" , when using the open() method, the first parameter is the file to be opened. If the parameter is only a file name, the file must be in the same path as the Python source file. So, how to get the path where Python is currently located? Python's os module provides related operations on file names and paths.

1 Import of os module

Use the import statement to import the os module, the code is as follows:

import os

2 Get the current path of python

Use the getcwd() function in the os module to get the current path, the code is as follows:

cwd = os.getcwd()

Among them, "cwd" is the abbreviation of "current working directory", that is, the current working path. The type of variable cwd is a string, which saves the path where Python is located.

3 Get the absolute path of the specified file

Obtain the relative path of the specified file through the os.path.abspath() function, the code is as follows.

abs_path = os.path.abspath(‘1.py’)

At this point, the variable abs_path is a string type, which stores the absolute path of "1.py". The absolute path is the path where Python is mentioned in "2 Get the current path of python" plus the file name.

It should be noted that the os.path.abspath() function will not verify whether the specified file exists, and will return its absolute path even if the file does not exist.

4 Determine whether the file exists

Use the os.path.exists() function to determine whether the specified file exists. The code is as follows:

os.path.exists(‘1.py’)

Return True if the file exists, False otherwise.

It should be noted that if the parameter is a file name, the specified file will be searched under the path where Python is mentioned in "2 Get the current path of python"; if the parameter is an absolute path of the file, the file will be searched under the specified path .

5 Determine whether it is a folder or a file

Use the os.path.isdir() function to judge whether it is a folder, and the os.path.isfile() function to judge whether it is a file. The code is as follows:

os.path.isdir(‘1.py’)
os.path.isfile(‘1.py’)

If it is a folder, os.path.isdir() returns True, otherwise it returns False; if it is a file, os.path.isfiler() returns True, otherwise it returns False.

6 Get all subfolders and files under the specified folder

Obtain all subfolders and files under the specified folder through the os.listdir() function, the code is as follows:

os.listdir(cwd)

Among them, the parameter of the os.listdir() function is the specified folder, and cwd is the folder where Python is located in "2 Get the current path of python". The return value of the os.listdir() function is a list, and the elements in the list are all subfolder names and file names under the folder.

Guess you like

Origin blog.csdn.net/hou09tian/article/details/131399201