简体   繁体   English

使用Python按扩展名将文件移动到根文件夹

[英]Move files by extension to root folder using Python

So I have a program that rips my movie collection but I'm trying to automate it further. 所以我有一个程序可以撕碎我的电影收藏,但我正在尝试进一步使其自动化。 My purpose is to search through each folder and look for a ".mkv" file and if it's found move it to the root folder then delete the original folder. 我的目的是搜索每个文件夹并查找“ .mkv”文件,如果找到该文件,请将其移至根文件夹,然后删除原始文件夹。

I have gotten this to work and it's operational but I'm curious how it could be wrote better. 我已经使它起作用并且可以运行,但是我很好奇如何更好地编写它。 Is there a way to essentially do this pseudo code? 有没有一种方法可以执行此伪代码?

loop each folder:
  if folder has files:
    if file extention is '.mkv':
      move file to '/media/movies/'

The folder structure is 文件夹结构为

C:/Users/Matthew/Desktop/New folder (2)
    - Test Movie
        ~ Test_Movie_t00.mkv
    - Alpha Movie
        ~ Alpha_Movie_t200.mkv
    - Greatest Movie Ever
        ~ Greatest_Movie_Ever_t100.mkv
    ~ Good Format Movie.mkv
    ~ Stackoverflow the Movie.mkv

Here is my code that works. 这是我的代码。

import os
import re

print("Running Cleaner\n")
directory = 'C:/Users/Matthew/Desktop/New folder (2)'
directorylength=len(directory)+1
folders = []
movies = []
for root, dirs, files in os.walk(directory, topdown=False):
    for name in dirs:
        #print(os.path.join(root, name)[strlength:])
        folders.append(os.path.join(root, name)[directorylength:])
for folder in folders:
    for file in os.listdir(directory + "/" + folder):
        if file.endswith(".mkv"):       
            #print(os.path.join(folder, file))
            movies.append(os.path.join(folder, file)[len(folder)+1:])
for folder in folders:
    for movie in movies:
        if os.path.exists(directory + "/" + folder + "/" + movie):
            file=folder + "/" + movie
            print("Found: " + file)
            newFile = re.sub('_t\d{2,}.mkv',".mkv",file)
            newFile = re.sub('_',' ',newFile)
            newFile = newFile[len(folder)+1:]
            print("Renaming to: " + newFile)
            os.rename(directory + "/" + file, directory + "/" + newFile)
    print("Removing empty folder: " + folder)
    os.rmdir(directory + "/" +folder)
print("\nFinished Cleaning up!")
  1. Keep a mapping of extensions to destination paths 保持扩展名到目标路径的映射

     mapping = {'mkv' : '/media/movies/', ... } 

    The nice thing about this is the support for multiple extensions in the future. 这样做的好处是将来会支持多个扩展。

  2. Check the extension by splitting with os.path.splitext 通过使用os.path.splitext拆分来检查扩展名

  3. Using shutil.move , you can specify the destination as a directory. 使用shutil.move ,您可以将目标指定为目录。 That simplifies things 这简化了事情

  4. if not os.listdir to check if a directory is empty. if not os.listdir ,则检查目录是否为空。 Otherwise, errors will be thrown (if the directory isn't empty) 否则,将引发错误(如果目录不为空)


mapping = {'mkv' : '/media/movies/', ... }
for root, dirs, files in os.walk(directory, topdown=False):
    for file in files:
        fullpath = os.path.join(root, file) 
        _, ext = os.path.splitext(fullpath)
        if ext in mapping:
            shutil.move(fullpath, mapping[ext])

    for dir in dirs:
        fullpath = os.path.join(root, dir)
        if not os.listdir(fullpath):
            os.rmdir(fullpath)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM