简体   繁体   中英

How to rename multiple files in a folder using python script

Say I have a folder with some files in it.

Name of the files are file1.txt, file2.txt, file3.txt, .... , etc.

Can you help me write a script that will rename all the files to file abc1.txt, bcd2.txt, cde3.txt, .... , etc. ?

Names of the files don't matter. I just want to see the code.

Also, I HAVE NO KNOWLEDGE OF CODING. I just want to see how someone would do it.

import os
os.rename('xyz.txt', 'new_name.txt')

Just take care of the file-path.

Let we consider that you are running the python program in that same directory then do this:-

import os
var1 = os.listdir()  # takes all file's name in a list
var0 = 0
for i in var1:
    os.rename(i, 'file{}'.format(var0))
    var0 += 1
# new names would be file1, file2 ...

PS: Always experiment on a dummy folder first; so that there would be no chance of loss.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM