运行python脚本时列表索引超出范围

2024-04-28 17:09:31 发布

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

索引器错误:列表索引超出范围

我在运行.py时不断出现此错误:

Traceback (most recent call last):
  File "dfm.py", line 32, in <module>
    sort_files_in_a_folder(mypath)
  File "dfm.py", line 14, in sort_files_in_a_folder
    filetype=file.split('.')[1]
IndexError: list index out of range 

对于本程序:

def sort_files_in_a_folder(mypath):
    '''
    A function to sort the files in a download folder
    into their respective categories
    '''
    files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
    file_type_variation_list=[]
    filetype_folder_dict={}
    for file in files:
        filetype=file.split('.')[1]
        if filetype not in file_type_variation_list:
            file_type_variation_list.append(filetype)
            new_folder_name=mypath+'/'+ filetype + '_folder'
            filetype_folder_dict[str(filetype)]=str(new_folder_name)
            if os.path.isdir(new_folder_name)==True:  #folder exists
                continue
            else:
                os.mkdir(new_folder_name)
    for file in files:
        src_path=mypath+'/'+file
        filetype=file.split('.')[1]
        if filetype in filetype_folder_dict.keys():
            dest_path=filetype_folder_dict[str(filetype)]
            shutil.move(src_path,dest_path)
    print(src_path + '>>>' + dest_path)
if __name__=="__main__":
    mypath='/Users/username/Downloads/'
    sort_files_in_a_folder(mypath)

我不太清楚如何纠正这个错误。有什么想法吗

我试图实现的是,每当有新的下载文件时,就管理我的下载文件夹文件,因此我通过区分格式类型将它们管理到不同的文件夹中


Tags: pathnameinpynewif错误files
1条回答
网友
1楼 · 发布于 2024-04-28 17:09:31

这表明在files中返回的不是所有东西都有'.'。要查看您的程序哪里有问题,请在for循环的开头打印file。那么错误之前的文件就是导致问题的文件,并且可能没有'.'

相关问题 更多 >