简体   繁体   English

如何在python中批量重命名具有相同名称和不同扩展名的多个文件

[英]How to bulk rename multiple files with same name and different extensions in python

I have a folder with a thousands of image files and JSON files, how can I bulk rename identical image files and JSON ?我有一个包含数千个图像文件和 JSON 文件的文件夹,如何批量重命名相同的图像文件和 JSON ?

For example例如

image.jpg -> 1.jpg
image.json -> 1.json

Here is what I tried which works fine for incremental label, how can I change it to also label files with same names alike ?这是我尝试过的对于增量标签工作正常的方法,如何将其更改为也标记具有相同名称的文件?

def renamed_files(path, label):

    i=0

    for filename in os.listdir(path):
        try:
            f, extension = os.path.splitext(path+filename)
            src=path+filename
            dst=path+str(i)+extension
            os.rename(src,dst)
            i+=1

        except Exception as e:
            print(e)
            i+=1

path="C://Users//other_images//"


renamed_files(path)

You can use two sets to store jpg filenames and json filesname.您可以使用sets来存储jpg文件名和json文件名。 Then, take intersection of both sets to take files that have the same name and rename them.然后,取两个集合的交集,取同名文件并重命名。 The code for the approach is given below.该方法的代码如下。

How can you change your code to do this?你怎么能改变你的代码来做到这一点?

First, create the two described sets.首先,创建两个描述的集合。 Now iterate through filenames.现在遍历文件名。 If file has extension=='jpg' then check if the filename exists in json_files set.如果文件具有扩展名=='jpg',则检查文件名是否存在于 json_files 集中。 If yes, rename both files, json and jpg.如果是,重命名两个文件,json 和 jpg。 Similarly for file with extension=='json'.对于扩展名为=='json'的文件也是如此。

import os
jpg_files = set()
json_files = set()
base_path = './'
for x in os.listdir(base_path):
    name, ext = x.split('.')
    if ext == 'jpg':
        jpg_files.add(name)
    elif ext == 'json':
        json_files.add(name)
counter = 1
for filename in jpg_files.intersection(json_files): # For files that are common (same names)
    os.rename(os.path.join(base_path,filename+'.jpg'),os.path.join(base_path,str(counter)+'.jpg')) # Rename jpg file
    os.rename(os.path.join(base_path,filename+'.json'),os.path.join(base_path,str(counter)+'.json')) # Rename json file
    counter += 1 # Increment counter

You could first store identical names with same extensions inside a collections.defaultdict , then rename the groups with more than one extension with os.rename() .您可以首先在collections.defaultdict存储具有相同扩展名的相同名称,然后使用os.rename()重命名具有多个扩展名的组。

As an example, if we had files image.jpg , image.json , image2.jpg , image2.json in a directory, we want to rename these files to 1.jpg , 1.json , 2.jpg , 2.json .例如,如果目录中有文件image.jpgimage.jsonimage2.jpgimage2.json ,我们想将这些文件重命名为1.jpg1.json2.jpg2.json

Demo:演示:

from os import rename
from os import listdir

from os.path import splitext
from os.path import join

from collections import defaultdict

def rename_same_name_files(path):
    filenames = defaultdict(list)

    # Group each name with extensions
    for file in listdir(path):
        name, ext = splitext(file)
        filenames[join(path, name)].append(ext)

    # Enumerate starting from 1 over each name : [extensions] grouping
    for idx, (name, extensions) in enumerate(filenames.items(), start=1):

        # Only rename files with more than one extension found
        if len(extensions) > 1:

            # Go through each extension
            for ext in extensions:

                # Get new path
                new_path = join(path, "%d%s" % (idx, ext))

                # Rename files
                rename(name + ext, new_path)

rename_same_name_files("PATH\TO\FILES")

Try os.scandir(directory) with string splitting and list popping, kind of like尝试os.scandir(directory)与字符串拆分和列表弹出,有点像

import os

def getFilename(file_with_extension):
    return file_with_extension.split('.')[:len(file_with_extension.split('.')-1]

def getExtension(file_with_extension):
    return '.'+file_with_extension.split('.')[len(file_with_extension.split('.')-1]

path = '/~'

files = os.scandir(path)    

n=0
old_name_without_extension=""
#Make sure it's sorted alphabetically so all similar files will be next to each other
files.sort()
while files:
   file = files.pop()
   name_without_extension = getFilename(file)
   extension = getExtension(file)
   if not old_name_without_extension == name_without_extension:
        n+=1
   old_name_without_extension = name_without_extension
   #Here copy your file with new filename using path, extension and desired naming scheme

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Python 中将所有具有不同扩展名的文件重命名为 .txt - Rename all files with different extensions to .txt in Python 如何使用Python检查具有相同名称的文件是否存在不同的扩展名 - How to check if file with same name exists with different extensions using Python 写一个 function 将两个同名文件(文件扩展名不同)移动到 python 同名文件夹中 - Writing a function to move two files with the same name (with different file extensions) to a folder with the same name in python 使用 Python 批量重命名具有不同部分的 txt 文件 - Bulk rename txt files with different parts using Python python-更改具有相同扩展名的多个文件 - python - Change multiple files of same extensions 如何使用在同一图形中插入的文本来重命名大量AutoCAD(.dwg)文件? - How to rename bulk of AutoCAD (.dwg) files with a text inserted in the same drawing? 如何在Python中重命名多个文件 - How to rename multiple files in Python 如何在python中导入具有相同名称的多个文件 - How to import multiple files with same name in python 如何在Python中使用不同的名称创建多个文件 - How to create multiple files with different name in Python 读取多个同名但扩展名不同的文件 Python - read multiple files with same name but different extension Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM