python文件命名文件夹_Python:根据文件名将文件移动到文件夹

I have a folder with 10 images that I wish to move into a new folder based on it's current filenames. I've successfully been able to move every images in the folder into a new folder, and as of now I've been successful at moving each image filename to its own folder but I've yet to figure out how to move all images with the same filename into one folder and the other to another folder. For example below I want to move the images accordingly.

1600_01.jpg ---> folder 1

1700_01.jpg ---> folder 1

1800_02.jpg ---> folder 2

1900_02.jpg ---> folder 2

2000_03.jpg ---> folder 3

2100_03.jpg ---> folder 3

This is my code thus far for moving the image files to a new folder by creating new folders based on it's filename. I got the part on making folders but I'm quite confused when it created separate image folders for all the images.

import os, shutil, glob

#Source file

sourcefile = 'Desktop/00/'

# for loop then I split the names of the image then making new folder

for file_path in glob.glob(os.path.join(sourcefile, '*.jpg*')):

new_dir = file_path.rsplit('.', 1)[0]

# If folder does not exist try making new one

try:

os.mkdir(os.path.join(sourcefile, new_dir))

# except error then pass

except WindowsError:

pass

# Move the images from file to new folder based on image name

shutil.move(file_path, os.path.join(new_dir, os.path.basename(file_path)))

This is what I got after I ran my script.

However, What I'm trying to do is shown in this image below:

解决方案

You can just try to use os.path.exists() to check if the folder exists, if it exists copy the jpg into it. By the way it's better if you use copy, because when you use move you are basically mixing everything up if you do something wrong.

import os, shutil

os.chdir("")

for f in os.listdir("folder"):

folderName = f[-6:-4]

if not os.path.exists(folderName):

os.mkdir(folderName)

shutil.copy(os.path.join('folder', f), folderName)

else:

shutil.copy(os.path.join('folder', f), folderName)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值