0

我制作了一个用于组织文件的脚本,并且运行良好。当它覆盖具有相同名称的文件时会发生我的问题。所以我在while循环中创建了一个变量[i],如果移动文件存在则添加。

from genericpath import isdir
import os
import shutil

# Set File Path ------------------------------
print(os.getcwd())
path = os.chdir(os.path.dirname(os.path.abspath(__file__)))

# Set Dict for files Extensions. -------------
IMAGES = (".jpeg", ".jpg", ".tiff", ".gif", ".bmp", ".png")

VIDEOS = (
    ".avi", ".flv", ".wmv", ".mov", ".mp4", ".webm", 
        ".vob", ".mng", ".qt", ".mpg", ".mpeg", ".3gp"
    )

ARCHIVES = (
    ".a", ".ar", ".cpio", ".iso", ".tar", ".gz", ".rz", 
        ".7z", ".dmg", ".rar", ".xar", ".zip"
    )

AUDIO = (
    ".aac", ".aa", ".aac", ".dvf", ".m4a", ".m4b", ".m4p",       
        ".mp3", ".msv", "ogg", "oga", ".raw", ".vox", ".wav", 
           ".wma"
    )

DOCUMENTS = (
    ".pdf", ".oxps", ".epub", ".pages", ".docx", ".doc", ".fdf",
         ".ods", ".odt", ".pwi", ".xsn", ".xps", ".dotx",     
             ".docm", ".dox", ".rvg", ".rtf", ".rtfd", ".wpd",
                ".xls", ".xlsx", ".ppt", "pptx", ".csv", ".txt", 
                   ".in", ".out"
    )

 PROGRAMS = (".exe", ".msi")

# Set list of Files in current dir. ----------
dir_list = os.listdir(path)

# Moving Files. ------------------------------
print('\n>>>> Start Organizing Files. <<<<\n')
for file in dir_list:
    i = 1
    if file == 'Folder-Organizer.py':
        pass

# Move [IMGs]. --------------------------------
    if file.endswith(IMAGES):
        while os.path.isfile(f'{path}\IMGs\{file}'):
            i += 1
            duplicated = os.path.splitext(file)
            file = f'{duplicated[0]}{i}{duplicated[1]}'
        
        shutil.copy(file, 'IMGs')
        os.remove(file)

但是每次循环运行时都会引发此错误。

in copyfile with open(src, 'rb') as fsrc:    
FileNotFoundError: [Errno 2] No such file or directory:
4

1 回答 1

1

对于每个人都有相同的问题,我找到了解决方案。shutil.move 引发错误(找不到文件)bcz while 循环在 python 环境中更改文件名,但不在目录中。因此,您需要先使用 os.rename 模块将文件更改为新名称,然后 shutil.move 完成其余的工作。

于 2022-02-28T17:35:23.477 回答