为什么代码会消失文件而无法正常工作?

时间:2019-12-29 18:58:45

标签: python automation

我尝试使用python编写脚本脚本,以自动将所有文件从下载文件夹分类到单独的文件夹,以便于查找文件。但是代码消失了许多文件,无法正常工作。该代码应进入downloads文件夹,并首先检查是否存在所有需要的文件夹。然后,它会扫描downloads文件夹中的所有项目,并按照特定的模式将它们排序到文件组中,然后将其移动到新创建的文件夹中。但是一些文本文件保留在downloads文件夹中,许多文件消失了。最后,该功能会将所有其他文件排序到“其他”文件夹中,甚至不起作用。

import os
import shutil

EXT_AUDIO = ['.wav', '.mp3', '.raw', '.wma']
EXT_VIDEO = ['.mp4', '.m4a', '.m4v', '.f4v', '.mov', '.avi', '.wmv', '.flv']
EXT_IMAGES = ['.jpeg', '.png', '.svg', '.gif', '.bmp', '.jpg']
EXT_DOCUMENTS = ['.txt', '.pdf', '.doc', '.docx', '.odt', '.html', '.csv']
EXT_EXECUTABLE = ['.exe', '.msi', '.jar']
EXT_ZIPRAR = ['.rar', '.zip']

path = 'C:/Users/ashka/Downloads'
os.chdir(path)

print('DOWNLOADS FOLDER CLEANUP')
print('Current directory: {}'.format(os.getcwd()))
print()

files = os.listdir()

#Create directories if they don't exist
DIRS = ['Executeable', 'Audio', 'Video', 'Images', 'Documents', 'Folder', 'Others', 'Compressed']

for i in DIRS:
    if not os.path.isdir(i):
        os.mkdir('./{}'.format(i))
        print('Directory {} successfully created!'.format(i))

#Run main script
for f in files:
    name, extension = os.path.splitext(f)

    if extension in EXT_IMAGES:
        shutil.move(f, './Images/{}'.format(f))
    elif extension in EXT_AUDIO:
        shutil.move(f, './Audio/{}'.format(f))
    elif extension in EXT_VIDEO:
        shutil.move(f, './Video/{}'.format(f))
    elif extension in EXT_EXECUTABLE:
        shutil.move(f, './Executeable/{}'.format(f))
    elif extension in EXT_DOCUMENTS:
        shutil.move(f, './Documents/{}'.format(f))
    elif extension in EXT_ZIPRAR:
        shutil.move(f, './Compressed/{}'.format(f))
    else:
        if os.path.isdir(name):
            if name not in DIRS:
                shutil.move(f, './Folder/{}'.format(f))
            else:
                shutil.move(f, './Others/{}'.format(f))

print('Cleanup finished!')

1 个答案:

答案 0 :(得分:0)

使用pathlib尝试此版本(由于f-strings,它需要Python 3.6 +):

from pathlib import Path

extensions = dict(
    Audios = ['.wav', '.mp3', '.raw', '.wma'],
    Videos = ['.mp4', '.m4a', '.m4v', '.f4v', '.mov', '.avi', '.wmv', '.flv'],
    Images = ['.jpeg', '.png', '.svg', '.gif', '.bmp', '.jpg'],
    Documents = ['.txt', '.pdf', '.doc', '.docx', '.odt', '.html', '.csv'],
    Executables = ['.exe', '.msi', '.jar'],
    Compressed = ['.rar', '.zip'],
    Others = [],
    Folders = []
)

path = Path('C:/Users/ashka/Downloads')

print('DOWNLOADS FOLDER CLEANUP')

for folder in extensions:
    f = path / folder
    if not f.exists():
        f.mkdir()
        print(f'Directory {f.name} successfully created!')
    elif not f.is_dir():
        raise Exception(f'{f.name} exists but it is not a directory!')

for obj in path.iterdir():
    if obj.is_file():
        if obj.suffix in extensions['Images']:
            obj.rename(path / f'Images/{obj.name}')
        elif obj.suffix in extensions['Audios']:
            obj.rename(path / f'Audios/{obj.name}')
        elif obj.suffix in extensions['Videos']:
            obj.rename(path / f'Videos/{obj.name}')
        elif obj.suffix in extensions['Executables']:
            obj.rename(path / f'Executables/{obj.name}')
        elif obj.suffix in extensions['Documents']:
            obj.rename(path / f'Documents/{obj.name}')
        elif obj.suffix in extensions['Compressed']:
            obj.rename(path / f'Compressed/{obj.name}')
        else:
            obj.rename(path / f'Others/{obj.name}')
    elif obj.is_dir() and obj.name not in extensions:
        obj.rename(path / 'Folder')
    else:
        print(f'Unknown file type: {f.name}')

print('Cleanup finished!')