Python to achieve batch renaming of the file code

  • 2020-04-02 09:41:02
  • OfStack

Here is the final code (implemented under Windows)
 
# -*- coding: cp936 -*- 
import os 
path = 'D:\ The picture \' 
for file in os.listdir(path): 
if os.path.isfile(os.path.join(path,file))==True: 
if file.find('.')<0: 
newname=file+'rsfdjndk.jpg' 
os.rename(os.path.join(path,file),os.path.join(path,newname)) 
print file,'ok' 
# print file.split('.')[-1] 

If it's a file (not a folder) and there's no '.' in the file name, add a suffix to the file and rename it

Some details to note:

1. If the folder specified by path is not the directory in which the program resides, the path inside the rename function must be an absolute path, otherwise a 'WindowsError: [Error 2]' Error is declared

2. When renaming, if the new file name already exists, a 'WindowsError: [Error 183]' Error is reported, so it is best to add some random strings to the new file name

3. If you change the file name or suffix, use the split() function

4. The find function returns' -1' if the specified string is not found
Blogger ma6174

Related articles: