Summary of common methods of python os module

The os module is commonly used to process files and manage paths. Here is a summary of the common methods of os.
os is a built-in python module, no pip install is needed when using it. Direct

import os 

1 Get the current system type

os.name      #分别是posix , nt , java, 对应linux/windows/java虚拟机
'nt'   

2 Display the path separator in the current system

os.sep
'\\'

3 Get current work directory get current work directory

os.getcwd()
'C:\\Users\\yuanwanli'

4 List files in the current directory

os.listdir()
['Desktop', 'Documents', 'Downloads', 'Music', 'My Documents', 'Videos', 'a.png']

5 Modify the file name

os.rename('a.png','b.png') # os.rename(oldName, newName) 
os.listdir()
['Desktop', 'Documents', 'Downloads', 'Music', 'My Documents', 'Videos', 'b.png']

6 Create a new directory

os.makedirs('test.txt')  
os.listdir()
['Desktop', 'Documents', 'Downloads', 'Music', 'My Documents', 'Videos', 'b.png', 'test']

7 Delete the file in the specified path

os.remove('b.png') 
os.listdir()
['Desktop', 'Documents', 'Downloads', 'Music', 'My Documents', 'Videos', 'test']

8 Delete the directory of the specified path

os.rmdir('test')
['Desktop', 'Documents', 'Downloads', 'Music', 'My Documents', 'Videos']

9 The absolute path of the file

os.path.abspath('Music')
 'C:\\Users\\yuanwanli\\Music'

10 The upper level absolute path of the file

os.path.dirname('C:\\Users\\yuanwanli\\Music') 
 'C:\\Users\\yuanwanli'

11 The last directory or file of the path, if the path ends with / or \, then a null value will be returned.

os.path.basename('C:\\Users\\yuanwanli\\Music')  
 'Music'

12 Split the path into path and file name

 os.path.split('C:\\Users\\yuanwanli\\Music')
 ('C:\\Users\\yuanwanli', 'Music')

13 Connection path and file name

os.path.join('C:\\Users\\yuanwanli', 'Music')
'C:\\Users\\yuanwanli\\Music'

14 Check whether the directory exists, and the existence is True

 os.path.exists('test')
 False

15 Check if it is a file

os.path.isfile('music')
 False

16 Check whether it is a directory

os.path.isdir('music')
 True

Guess you like

Origin blog.csdn.net/weixin_43705953/article/details/109167273