将文件重命名为数字的脚本会跳过某些文件

时间:2017-09-14 21:31:24

标签: python-3.x iteration ubuntu-16.04

我有一个脚本可以将目录中的所有.mp3个文件重命名为连续的数字:

dir = os.getcwd() if len(sys.argv) == 1 else sys.argv[1] 
os.chdir(dir)
filenames_in_dir = os.listdir(dir)

mpr_search_expr = re.compile('.mp3')

currNumber = 0;
for filename in filenames_in_dir:
    # ignore non-mp3 files
    if mpr_search_expr.search(filename):
        #change title to number
        audiofile = eyed3.load(filename)
        audiofile.tag.title = get_valid_name_from_index(currNumber)
        audiofile.tag.save()

        #change name to number
        os.rename(filename, get_valid_name_from_index(currNumber))
        currNumber += 1

将名称功能定义为:

def get_valid_name_from_index(index):
'''index must be 0-based, return value is >=1'''
valid_name = str(index + 1) + '.mp3'

if index + 1 < 10 :
    valid_name = '0' + valid_name

return valid_name

问题是,它似乎跳过了目录中的22或21个元素: skipped

它可以在不同的运行中跳过这个数字:

skipped other number

我找不到错误......

1 个答案:

答案 0 :(得分:1)

问题是你的for循环增加i的值,即使对于非mp3文件也是如此。

for i in range(len(filenames_in_dir)):
    # ignore non-mp3 files BUT INCREMENT value of i
    if mpr_search_expr.search(filenames_in_dir[i]):
        os.rename(filenames_in_dir[i], get_valid_name_from_index(i))
你应该做点什么

j = 0
for i in range(len(filenames_in_dir)):
    # ignore non-mp3 files
    if mpr_search_expr.search(filenames_in_dir[i]):
        j+= 1
        os.rename(filenames_in_dir[i], get_valid_name_from_index(j))