Python:根据文件名将文件移动到文件夹 [英] Python: Moving files to folder based on filenames

查看:2006
本文介绍了Python:根据文件名将文件移动到文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含10个图像的文件夹,我希望根据它的当前文件名移动到新文件夹中。我已经成功地将文件夹中的每个图像移动到一个新文件夹中,到目前为止,我已经成功地将每个图像文件名移动到它自己的文件夹,但我还没弄明白如何移动所有图像相同的文件名放入一个文件夹,另一个放到另一个文件夹。例如下面我想相应地移动图像。

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 --->文件夹1

  • 1700_01.jpg --->文件夹1

  • 1800_02.jpg --->文件夹2

  • 1900_02.jpg --->文件夹2

  • 2000_03.jpg --->文件夹3

  • 2100_03.jpg --->文件夹3

  • 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:

推荐答案

您可以尝试使用os.path .exists()检查文件夹是否存在,如果存在则将jpg复制到其中。顺便说一句,如果你使用副本会更好,因为当你使用移动时,如果你做错了什么,你基本上就把所有东西混在一起。

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("<abs path to desktop>")

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)

< img src =https://i.stack.imgur.com/EmfR2.pngalt =在此输入图像说明>

这篇关于Python:根据文件名将文件移动到文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆