Summary of os file operation module methods in Python with mind map
The os module provides a very rich method for handling files and directories. This article will briefly introduce the commonly used methods, as shown in the following table:
The specific operations are as follows
import os
- Switch working path
os.chdir("C:\软件")
- Get the current working directory, that is, the directory path where the current Python script works:
os.getcwd()
'C:\\软件'
- Return all file and directory names in the specified directory
os.listdir()
['basic-miktex-20.12-x64.exe',
'EViews 10.0 64位.zip',
'Navicat Keygen Patch v5.6.0 DFoX.exe',
'navicat150_premium_cs_x64.exe',
'nbpreview-master',
'pandoc-2.0.1.1-windows.msi',
'Snipaste-2.3.5-Beta-x64',
'typora-setup-x64_0.9.78.exe']
- Function to delete a file
os.remove("测试\测试.txt")
- Delete multiple directories
os.removedirs("测试")
- Create a multi-level directory
os.makedirs("测试\测试")
- Check if the given path is a file
os.path.isfile("EViews 10.0 64位.zip")
True
- Check if the given path is a directory
os.path.isdir("EViews 10.0 64位.zip")
False
- Determine whether it is an absolute path
os.path.isabs(r"C:\软件")
True
- Check whether the given path actually exists
os.path.exists(r"C:\user")
False
- Return the directory name and file name of a path
os.path.split('typora-setup-x64_0.9.78.exe')
('', 'typora-setup-x64_0.9.78.exe')
- Separate extension
os.path.splitext('typora-setup-x64_0.9.78.exe')
('typora-setup-x64_0.9.78', '.exe')
- Run shell commands
os.system()
0
- Reorder
os.rename(old,new)
- Get file size
os.path.getsize(filename)
0
- Indicate which platform you are using
os.name
'nt'
For Windows, it is'nt', and for Linux/Unix users, it is'posix'
This is the end, if it helps you, welcome to like and follow, your likes are very important to me