python - 根据名称将多个文件从单个文件夹移动到多个文件夹

标签 python python-3.x directory

我有一个文件夹,其中包含以下类型的文件-
boxer_1.jpg
boxer_2.jpg
american_bulldog_120.jpg
american_bulldog_119.jpg
这里每个字母名称代表动物的品种,数字代表其数量。
我想根据文件名创建文件夹,然后将文件放入各自的文件夹中。
我希望文件夹名称只是字母名称。

我已成功根据文件名创建文件夹。 首先,我从文件名中删除了数字、下划线和扩展名,然后将它们放入列表中。 然后我从列表中创建了文件夹。

  files = os.listdir("data_path")
  import re
  cleaned_files = []
  for each in files: # To remove the digits and underscore.
     cleaned_files.append(re.sub(r'[0-9\_]','',each))

  new_files = [] # To remove the .jpg extension
  for each in distinct_files:
     new_files.append(re.sub('.jpg','',each))

  from collections import OrderedDict # To make list distinct 
  distinct_files = list(OrderedDict.fromkeys(new_files))

  path_dir = 'Modified_Dataset_Path' #Creation of folders
  for folder in distinct_files:
     os.mkdir(os.path.join(path_dir,folder))

我无法从这里继续,如何将文件放置到相应的文件夹中。 也欢迎任何其他解决此问题的方法。 P.S-数据集是 Oxford IIIT Pet dataset如果有人想尝试测试他们的方法。

最佳答案

因此您可以对每个文件进行相同的处理,然后将其移动到该目录。


cleaned_files = []
new_files = []
for f in files
    cleaned_files=(re.sub(r'[0-9\_]','',f))
    new_files=(re.sub('.jpg','',cleaned_files))
    shutil.copy(os.path.join(data_path,f),os.path.join(Modified_Dataset_Path,new_files))

data_path 是原始文件所在的目录,Modified_Dataset_Path 是所有新目录所在的目录。

关于python - 根据名称将多个文件从单个文件夹移动到多个文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56758501/

相关文章:

c# - 根据文件C#的位置获取目录

python - 当我尝试安装 ordered-set 时出现 UnicodeDecodeError

android - 如何编写算法来查看目录是否包含 jpg 文件(子文件夹)

python - pygtk 中的多线程

python - 2 组并集不包含所有项目

python - Tensorflow:子张量的reduce_mean并连接结果

python - 如何与普通用户一起使用 root 创建的套接字

Python错误: Cannot find the file specified

python - 如何在日志处理程序中指定 str.format() 样式?

python - 在 Django 中通过 REST API 登录