重命名,移动和删除原始目录

时间:2016-02-29 05:19:13

标签: python-3.x shutil os.walk

我正在尝试修改一个脚本,该脚本将遍历给定目录并重命名,移动和删除原始目录。每个目录都有一个*.mp4文件和一个包含*.jpg个文件的子文件夹。我在重命名和移动文件时删除原始目录时遇到问题。到目前为止:

import datetime, os, re, shutil, logging, smtplib

logging.basicConfig(level = logging.INFO, format = ' %(asctime)s - %(levelname)s - %(message)s')
#logging.disable(logging.info)

path = '\\\\RT-N66U\\sda2\\Documents'
desired_text1 = re.compile(r'^\d{3}_[a-zA-Z]+\d{3}.jpg')
desired_text2 = re.compile(r'^\d{3}_[a-zA-Z]+_\d{3}.jpg')
renamed_files = ''

for folderName, subfolders, filenames in os.walk(path):
    if folderName.startswith(path + '\\GEO-'):
            logging.info('The current folder is ' + folderName)

            for subfolder in subfolders:
                    if subfolder.startswith('Pics'):
                            pic_folder = subfolder

            for filename in filenames:                        
                    if filename.endswith('.mp4'):
                            changed_date = datetime.datetime.strptime(filename[3:17], '%b %d, %Y').strftime('%y.%m.%d') # Changes the name of the date to the desired format
                            year = datetime.datetime.strptime(filename[3:17], '%b %d, %Y').strftime('%Y')
                            name = filename[20:-25]
                            name = name.lower()
                            modified_name = '.'.join(re.findall('\S+', name))
                            final_name = 'geo.' + changed_date + '.' + modified_name

                    if not os.path.exists('\\\\RT-N66U\\sda2\\Me\\GEO\\%s\\%s\\%s' % (year, changed_date[3:5], final_name)):            
                            os.makedirs('\\\\RT-N66U\\sda2\\Me\\GEO\\%s\\%s\\%s' % (year, changed_date[3:5], final_name)) 

                    if not os.path.exists('\\\\RT-N66U\\sda2\\Me\\GEO\\%s\\%s\\%s\\%s' % (year, changed_date[3:5], final_name, pic_folder)):
                            os.makedirs('\\\\RT-N66U\\sda2\\Me\\GEO\\%s\\%s\\%s\\%s' % (year, changed_date[3:5], final_name, pic_folder))        

                    if filename.endswith('.mp4'):
                            logging.info(filename)
                            os.rename(folderName + '\\' + filename, '\\\\RT-N66U\\sda2\\Me\\GEO\\%s\\%s\\%s\\%s.mp4' % (year, changed_date[3:5], final_name, final_name))

                    # This part will logg and rename the files by adding a '_'
                    mo1 = desired_text1.search(filename)
                    mo2 = desired_text2.search(filename)

                    if mo1:
                            logging.info(folderName + '\\' + filename)
                            os.rename(folderName + '\\' + filename, '\\\\RT-N66U\\sda2\\Me\\GEO\\%s\\%s\\%s\\%s\\%s_%s' % (year, changed_date[3:5], final_name, pic_folder, filename[:-7], filename[-7:]))
                            renamed_files += filename + ' -> ' + filename[:-7] + '_' + filename[-7:] + '\n'

                    elif mo2:
                            logging.info(folderName + '\\' + filename)
                            os.rename(folderName + '\\' + filename, '\\\\RT-N66U\\sda2\\Me\\GEO\\%s\\%s\\%s\\%s\\%s' % (year, changed_date[3:5], final_name, pic_folder, filename))
                            renamed_files += filename + '\n'  

    # This part will check if the directory is empty and delete it if so
    if os.listdir(folderName) == []:
            logging.info(folderName)
            shutil.rmtree(folderName)

最终发生的是,如果所有子目录都为空并且主目录为空,则将删除所有子目录。我希望删除主目录,因为所有文件都已被移动。有没有办法在for声明中完成此任务?

1 个答案:

答案 0 :(得分:0)

如果您的意思是删除主for循环中名为folderName的目录,我认为这不可能,因为您正在迭代包含它的对象。就像在for i in this_list:内部,你想从this_list中删除一个对象。在您退出循环之前,这是不可能的。

为了达到你想要的效果,我会编写一个函数来递归到文件夹树中。这个想法是这样的:

def process_folder(folder_name):
    do some stuff on files
    get the subfolders of folder_name
    for f in subfolders:
        process_folder(subfolder_name)
        if subfolder_name is empty, delete it
    maybe do some other stuff on files

并在主脚本中调用process_folder(path)。 (即使它是空的,这也只会留下顶级文件夹,所以请确保您不想删除它;或者在更高级别调用process_folder,或者添加指令以删除它它也是空的。