Skip to main content
 首页 » 编程设计

Python之将文件移动到包含部分文件名的文件夹

2025年02月15日12yyy_WW

我已经尝试了脚本的多次迭代,但现在又回到了盯着空白的 Notepad++

我有 6k 个文件夹,格式如下:

Reading Festival 1999 
Reading Festival 2000 
Reading Festival 2001 
Leeds Festival 1999 
Leeds Festival 2000 
Leeds Festival 2001 
Download Festival 2005 
Download Festival 2006 
... 

在同一个文件夹中,我有一长串文件,格式为

Artist at {Festival Name} by Photographer - UID 

其中Artist是在音乐节上演奏的人,Photographer是拍摄的人,UID是唯一的ID

我的问题是我将如何遍历文件夹,对于每个文件夹,查看文件名是否包含文件夹的名称,如果包含,则将文件移动到那里。

import os 
rootdir = 'C:\Users\Alan\Desktop\VF' 
 
for subdir, dirs, files in os.walk(rootdir): 
    for d in dirs: 
        for file in files: 
            the_file = os.path.join(subdir, file) 
            if d in the_file: 
                new_loc = subdir + '\\' + d + '\\' + file 
                os.rename(the_file, new_loc) 

我有这段代码,我相信它应该可以工作,但我担心它会读取文件夹中已有的所有图像。我该如何避免这种情况?

请您参考如下方法:

因为你的文件和文件夹在同一层,你不需要使用os.walk()来遍历目录树。 os.listdir() 将代替,正如您在评论中指出的那样。一种解决方案是使用 os.listdir() 获取目录和文件列表,并以与之前相同的方式找到 new_loc 名称,使用 in 而不是正则表达式。

folders = [d for d in os.listdir('.') if os.path.isdir(d)] 
files = [f for f in os.listdir('.') if os.path.isfile(f)] 
for d in folders: 
   for f in files: 
      if d in f: 
          new_loc = subdir + '\\' + d + '\\' + file 
          os.rename(the_file, new_loc) 

这里的逻辑和你的差不多,只是获取目录和文件的方式不同!