循环停止,重命名/移动文件时没有任何错误消息

2024-10-01 13:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的程序中,我试图重命名我的目录中存在的文件。但是,每次我运行不同数量的文件被重命名和程序停止没有任何错误消息

'''
Created on 08-Jul-2017

@author: Pranav
'''
import os
import re
from shutil import move

class MyPatterns:
    brackets = "([\(\[]).*?([\)\]])"
    extra_spaces_pattern = " +"

class MyConstants:
    #dir_path = "D:\Other\Books\Knowledge"
    space = ' '
    underscore = '_'    
    blank = ''

def resolve_filenames(dir_path,filename):
    new_file_name = re.sub(MyPatterns.brackets,MyConstants.blank,filename)
    new_file_name = re.sub(MyPatterns.extra_spaces_pattern,MyConstants.space,new_file_name)
    new_file_name = new_file_name.replace(MyConstants.underscore, MyConstants.space)
    new_file_name = new_file_name.title()
    move(os.path.join(dir_path,filename),os.path.join(dir_path, new_file_name))


base_path = "D:\Other\Books"
directories = os.listdir(base_path)
print('Starting process to resolve file names from base path : {}: '.format(base_path))
for d in directories:
    dir_path = os.path.join(base_path, d)
    print('Resolving files for directory : {} '.format(d))
    for i,fname in enumerate(os.listdir(dir_path)):
        print(i,fname)
        resolve_filenames(dir_path, fname)

Tags: pathnameimportrenewbaseosdir