简体   繁体   中英

Removing Integer from end of filenames in python

I have a list of files, each with the same name. When they were copied into my directory, the OS automatically added a (1), (2), etc to differentiate them from one another. They are different versions of the same file.

How would I go about systematically removing the numeric addition from the end of the strings? Directly after this step I will be adding on each file's creation time to the end.

ex.

file.pdf
file (1).pdf
file (2).pdf
file (3).pdf

would then become

file-2015-08-08T10:06:59Z.pdf
file-2015-07-08T10:06:59Z.pdf
file-2015-06-08T10:06:59Z.pdf
file-2015-05-08T10:06:59Z.pdf

To do it in current directory:

import os, time
for filename in os.listdir("."):
    if filename.startswith("file"):
        os.rename(filename, filename[4:-4] + time.ctime(os.path.getctime(filename)) + ".pdf")

just substitute "file" for whatever the beginning of the file name is before the numbers and the 4 in [4:-4] with the length of that string. If you wanna display the time in a different way than ctime does, just substitute time.ctime(os.path.getctime(filename)) for something that returns the string for that time.

Based on @Joan's and @dietbacon's solutions:

import os
import re
import time
for filename in filenames:
    new_name = re.sub("\([0-9]+\)",time.ctime(os.path.getctime(filename))+".pdf", filename)
    os.rename(filename, new_name)

Here is a solution for all file extensions

import os
import re
import datetime

dirname = os.path.abspath("./test") # target directory
for filename in os.listdir(dirname):
    filepath = os.path.join(dirname, filename)
    fname, fext = os.path.splitext(filename)
    match = re.search("(.+?)\s\([0-9]+\)",fname)
    if match:
        fname = match.group(1)
    ctime = os.path.getctime(filepath)
    ctime = datetime.datetime.utcfromtimestamp(ctime).isoformat()
    newfilepath = os.path.join(dirname, fname + "-" + ctime + fext)
    os.rename(filepath, newfilepath)

Note: colon is not permitted in file names in windows.

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