使用python重命名多个图像并保存到另一个文件夹中
我在一个文件夹中有100个图像,我想将它们全部重命名。例如,Car.1.jpg、Car.2.jpg、Car.3.jpg等等,然后将它们保存到另一个文件夹中。我写的代码重命名所有的图像,因为我想,但它保存在同一个文件夹中的图像存在。我想重命名所有图像,并将原始图像名称保留在目录中,然后将重命名后的图像复制到另一个目录中使用python重命名多个图像并保存到另一个文件夹中,python,Python,我在一个文件夹中有100个图像,我想将它们全部重命名。例如,Car.1.jpg、Car.2.jpg、Car.3.jpg等等,然后将它们保存到另一个文件夹中。我写的代码重命名所有的图像,因为我想,但它保存在同一个文件夹中的图像存在。我想重命名所有图像,并将原始图像名称保留在目录中,然后将重命名后的图像复制到另一个目录中 import os from tqdm import tqdm path = './training_data/car/' def image_rename(): cn
import os
from tqdm import tqdm
path = './training_data/car/'
def image_rename():
cnt = 1
for img in tqdm(os.listdir(path)):
if os.path.isfile(path+img):
filename, file_extention = os.path.splitext(path+img)
os.rename(os.path.join(path, img), os.path.join(path,
str('car.') + str(cnt) + file_extention))
cnt +=1
image_rename()
添加一个变量
output\u path
,指向要将文件导出到的文件夹,然后在os.rename()
的第二个参数中使用此变量,如下所示:
import os
from tqdm import tqdm
path = './training_data/car/'
output_path = './training_data/output_folder/'
def image_rename():
cnt = 1
for img in tqdm(os.listdir(path)):
if os.path.isfile(path+img):
filename, file_extention = os.path.splitext(path+img)
os.rename(os.path.join(path, img), os.path.join(output_path,
str('car.') + str(cnt) + file_extention))
cnt +=1
image_rename()
确保在系统中创建输出文件夹(例如,使用mkdir
。您应该尝试使用
os.chdir
将更改使用完整路径而不是相对路径(例如path='/home/armin/training\u data/car/
)的工作方向。重命名是一个mv
使用shutil.copy
instead@djangoliv谢谢,我以前做过这个,但我的问题是重命名后,我的所有图像都移动到输出路径。我想将我的图像及其名称保留在存在的文件夹中,并将图像重命名为另一个文件夹。重命名后移动图像。我不想在重命名后移动图像。我的意思是,我想把我的图像和名称保存在文件夹中,然后用我想要的名称将图像复制到另一个文件夹中。要找到答案,我必须使用shutil.copy(“path/to/current/file.foo”,“path/to/new/destination/for/file.foo”)
import shutil
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")