我希望包含y.png文件的x文件夹的名称为z.png

2024-05-07 06:11:08 发布

您现在位置:Python中文网/ 问答频道 /正文

你会发现我的代码我不是PythonPro,但我做了一切来成为它

import os, sys
os.listdir(os.getcwd())


Out[3]: ['.ipynb_checkpoints',
         'helmet_10_0.png',
         'helmet_10_1.png',
         'helmet_10_10.png',

I wish

Out[0]: ['casque_Chantier_10_0.png',
         'casque_Chantier_10_10.png',
         'casque_Chantier_10_100.png'

诸如此类


source = 'D:\\Chasse_Au_tressor\\base_agmt\\extractedFrames_step_5\\helmet_10_0.png'


dest = 'D:\\Chasse_Au_tressor\\base_agmt\\extractedFrames_step_5\\Casque_Chantier_10_0.png'

os.rename(source, dest)
Out[2]: ['casque_Chantier_10_0.png',
         'helmet_10_1.png',
         'helmet_10_10.png',
         'helmet_10_100.png',
         'helmet_10_101.png',

我不能循环使用“glob”并重命名所有文件

<ipython-input-33-1a271eebe4a0> in <module>
      1 for i in source:
      2     if i != dest:
----> 3         os.rename(i,dest)

FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable: 'D' -> 'D:\\Chasse_Au_tressor\\base_agmt\\extractedFrames_step_5\\Casque_Chantier_{*}.png'

我想要casque_Chantier_{index=1}.png上的图像


Tags: sourcebasepngosstepoutdestau
3条回答

以下内容适用于Python3.6

您将需要从字符串库中替换以将“头盔”更改为“casque_Chantier”:

import shutil
import os
dir_path = os.getcwd()

for filename in os.listdir(dir_path):
    src = os.path.join(dir_path, filename)
    dst = os.path.join(dir_path, filename.replace("helmet", "casque_Chantier"))
    shutil.move(src, dst)

下面的代码遍历每个文件,并根据需要重命名该文件。它将“头盔”部分替换为“头盔”。 我已将其设置为与要重命名的文件在同一文件夹中运行

import os

for file in os.listdir():
    os.rename(file, file.replace("helmet_","casque_Chantier_")
import os, sys

directory = os.getcwd()
filenames = os.listdir(directory)

renamed_filenames = [f.replace('helmet', 'casque_Chantier') for f in filenames]

for i in range(len(filenames)):

    source_filepath = os.path.join(directory, filenames[i])
    dest_filepath = os.path.join(directory, renamed_filenames[i])

    os.rename(source_filepath, dest_filepath)

相关问题 更多 >