Summary of os file operation module methods in Python with mind map

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:

Mind map of common methods of os module

The specific operations are as follows

import os
  1. Switch working path
os.chdir("C:\软件")
  1. Get the current working directory, that is, the directory path where the current Python script works:
os.getcwd()
'C:\\软件'
  1. 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']
  1. Function to delete a file
os.remove("测试\测试.txt")
  1. Delete multiple directories
os.removedirs("测试")
  • Create a multi-level directory
os.makedirs("测试\测试")
  1. Check if the given path is a file
os.path.isfile("EViews 10.0 64位.zip")
True
  1. Check if the given path is a directory
os.path.isdir("EViews 10.0 64位.zip")
False
  1. Determine whether it is an absolute path
os.path.isabs(r"C:\软件")
True
  1. Check whether the given path actually exists
os.path.exists(r"C:\user")
False
  1. 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')
  1. Separate extension
os.path.splitext('typora-setup-x64_0.9.78.exe')   
('typora-setup-x64_0.9.78', '.exe')
  1. Run shell commands
os.system() 
0
  1. Reorder
os.rename(old,new)
  1. Get file size
os.path.getsize(filename)
0
  1. 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

Guess you like

Origin blog.csdn.net/qq_45176548/article/details/111601730