python renames all file instances in the folder based on list
- 2021-01-03 20:56:27
- OfStack
As shown below:
# coding = utf-8
import os
path = "D:\\chunyu"# You want to rename the folder where all your files are stored
filelist = os.listdir(path) # All files under this folder (including folders)
list = []
fileopen = open('D:\chunyu.txt','r')# A collection of all the names you want to rename later, which is the file name with the file extension removed
i =0
for file in filelist:
print(file)
for line in fileopen:
line = line.strip('\n')
list.append(line)# read txt Write a set of all the names inside list file
print(list)
fileopen.close()
for file in filelist: # Iterate over all the files
Olddir=os.path.join(path,file) # The original file path
if os.path.isdir(Olddir): # If it is a folder, skip it
continue
filename=os.path.splitext(file)[0] # The file name
filetype=os.path.splitext(file)[1] # File extension
Newdir=os.path.join(path,str(list[i])+filetype)
os.rename(Olddir,Newdir)# rename
print(Olddir+" has changed as "+Newdir)
i = i+1
print(i)