python os. rename example usage

  • 2021-08-12 03:12:40
  • OfStack

It is not difficult to use the os. rename method, The main function is applied to renaming files, Normally, we want to change the file on the desktop, directly select the right-click software, and then rename it. This is our most common way. If you want to change the file name in py, it is not difficult. In fact, the methods that are often used are basically very simple to operate. 1 Let's take a look ~

Python os. rename () Method Instructions

Syntax: os. rename (src, dst)

Parameters: src, dst

Use example:


import os 
os.rename('.txt')

Batch change file name implementation code:


#-*- coding: UTF-8 -*-
import os
filenames = os.listdir(os.getcwd())
for name in filenames:
print(name)
for num in range(0,len(filenames)):
if(num<10):
print()
print(filenames[num])
os.rename(filenames[num],'0'+str(num)+'.png')

Conceptual expansion

The os. rename () method is used to rename a file or directory from src to dst, throwing OSError if dst is an existing directory.

Grammar

The syntax format of the rename () method is as follows:

os.rename(src, dst)

Parameter

src Directory name to modify

dst Modified Directory Name

Return value

This method has no return value

This method can rename files and directories,

If the file or directory corresponding to the src parameter does not exist, it will be error-guaranteed.

If the file or directory corresponding to the dst parameter already exists, an error will also be reported


Related articles: