简体   繁体   中英

Rename All Files in a Directory with consecutive numbers in Python

I would like to rename all file (the filenames have no clear pattern) into filenames with consecutive numbers eg:

Files in Directory:

agh_uio78.jpg hhaq23klp.png mickey.tiff

into

001.jpg 002.png 003.tiff

This will give me a result with no extension:

import os

FList = os.listdir(os.getcwd())
FListC = FList[1:]

m = 0
for i in FListC:
    os.rename(i,str(m))
    m = m+1

Result:

1 2 3

import os

FList = os.listdir(os.getcwd())
FListC = FList[1:]

m = 0
for i in FListC:
    fileExtension = os.path.splitext(i)[1]
    os.rename(i,str(m)+fileExtension)
    m = m+1

You forgot to save the extension of the file.
Above code will grab the file's extension and concatenate to your incremented file name

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