Simple Use and Rename Operation of os Module in Python
- 2021-11-01 03:41:54
- OfStack
Preface
OS module although the basic time has been learned, but who let me belong to the kind of people do not immediately forget it, so in the next crawling a certain indescribable men like the site, in the encounter crawling down the data need to save, you need to use the OS module
Basic Review of OS Module
Review the basics first
The OS module is used to manipulate folders (based on my understanding)
import os
os.mkdir("path") # Create the path
Then, the foundation is gone. Yes, I learned this when I studied the basic OS module. At that time, it was enough
Small Application of OS Module
This is what I used when I was writing a crawler applet
1. An error was reported when the folder existed while saving the file
import os
path = " File path "
if not os.path.exists(path):
os.mkdir(path)
If path does not exist, it is created, and if it does, it is not created
2. View the path of the current file
import os
print(os.getcwd())
This is quite useful. Before writing crawlers with mobile phones, it is the current path seen by this that can save the data. As for what data is crawling, this is of course the kind of O that men love to watch. Haha ~
3. Copy the file and rename the copy
import os
# No. 1 1 Methods
os.rename(" The name of the file to copy ", " Rename the copied file ")
# No. 1 2 Methods
os.system("copy The name of the file to copy Rename the copied file ")
# This method is to open the cmd Rename is equivalent to the code to help you open it cmd And typed this command, noting that the file name needs to be an absolute path
Simple Rename Operation of os Module for python
# coding=utf-8
import os
# Will 1355..ts The file name is changed to 1355.ts
# File name directory address to modify
path = "D:/video/"
# Get all files in the current directory
dirlist = os.listdir(path)
for name in dirlist:
# If the extension is .ts
if name[-3:] ==".ts":
# Find the first 1 Position of points
i = name.find(".")
# The new name is 1355 + ".ts"
newname = name[:i]+".ts"
# Rename operation
os.rename(path+name,path+newname)