而循环以增加文件名称价值

发布于 2025-01-18 01:25:05 字数 2096 浏览 0 评论 0原文

我有一个函数可以根据扩展名组织目录中的文件。例如,它创建一个名为 txt 的文件夹,并将所有文本文件移动到该文件夹​​中。当已经有一个txt文件夹并且有一个文本文件时,它会自动将其成功移动到该​​文件夹​​中。问题是它不会移动与 txt 目录中的文件同名的文件。

输入图片此处描述

这是目录,txt 文件夹内包含一个名为 Text.txt 的文件,该目录还包含一个名为 Text.txt 的文件,因此它无法移动将其放入文件夹中,我尝试使用 while 循环,但由于多个 for 循环和复杂性,我无法在正确的位置使用它。谢谢!

def all_extensions_category(folder_to_track):
    if check_files(folder_to_track) == True:
        for file in os.listdir(folder_to_track):
            if os.path.isdir(os.path.join(folder_to_track, file)) == False and os.listdir(folder_to_track).__len__() != 0:
                try:
                    file_mappings = collections.defaultdict()
                    for filename in os.listdir(folder_to_track):
                        if not os.path.isdir(os.path.join(folder_to_track, filename)):
                            file_type = filename.split('.')[-1]
                            file_mappings.setdefault(file_type, []).append(filename)
        
                    for folder_name, folder_items in file_mappings.items():
                        folder_path = os.path.join(folder_to_track, folder_name)
                        folder_exists = os.path.exists(folder_path)
    
                        if not folder_exists:
                            os.mkdir(folder_path)
        
                        for folder_item in folder_items:
                            source = os.path.join(folder_to_track, folder_item)
                            destination = os.path.join(folder_path, folder_item)
                            os.rename(source, destination)
                    
                    return print("Successfully organized files based on extension")
                            
                except Exception as e:
                    return print(f'{folder_to_track}: is either empty or not organizable')
    
    else:
        return print(f'{folder_to_track}: is either empty or not organizable')

I have a function that organizes files in a directory based on extensions. For example, it makes a folder called txt and moves all text files into that folder. When there is already a txt folder and if there is a text file then it will automatically move it into that folder successfully. The problem is it won't move a file with the same name as the file in the txt directory.

enter image description here

This is the directory and inside the txt folder contains a file named Text.txt and the directory also contains a file named Text.txt, thus it's not able to move it into the folder, I tried using a while loop but I am not able to use it in the right place due to multiple for loops and complexity. Thanks!

def all_extensions_category(folder_to_track):
    if check_files(folder_to_track) == True:
        for file in os.listdir(folder_to_track):
            if os.path.isdir(os.path.join(folder_to_track, file)) == False and os.listdir(folder_to_track).__len__() != 0:
                try:
                    file_mappings = collections.defaultdict()
                    for filename in os.listdir(folder_to_track):
                        if not os.path.isdir(os.path.join(folder_to_track, filename)):
                            file_type = filename.split('.')[-1]
                            file_mappings.setdefault(file_type, []).append(filename)
        
                    for folder_name, folder_items in file_mappings.items():
                        folder_path = os.path.join(folder_to_track, folder_name)
                        folder_exists = os.path.exists(folder_path)
    
                        if not folder_exists:
                            os.mkdir(folder_path)
        
                        for folder_item in folder_items:
                            source = os.path.join(folder_to_track, folder_item)
                            destination = os.path.join(folder_path, folder_item)
                            os.rename(source, destination)
                    
                    return print("Successfully organized files based on extension")
                            
                except Exception as e:
                    return print(f'{folder_to_track}: is either empty or not organizable')
    
    else:
        return print(f'{folder_to_track}: is either empty or not organizable')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请别遗忘我 2025-01-25 01:25:05

如果您想创建数量不断增加的文件,例如 Windows 在复制具有相同名称的文件时所做的那样,请将您的 os.rename() 替换为以下函数:

def moveIncrementing(source, destination):
    i = 0
    while True:
        try:
            return os.rename(source, f"{destination}_{i}" if i else destination)
        except OSError as ex:
            i+=1
            print(ex)

它将继续尝试移动文件,直到操作成功通过。只是警告,它会在文件扩展名后添加数字,因此文件的扩展名将无法正确识别。但这是我留给你的练习。

If you want to create files with increasing numbers like e.g. Windows does when copying a file with the same name, replace your os.rename() with following function:

def moveIncrementing(source, destination):
    i = 0
    while True:
        try:
            return os.rename(source, f"{destination}_{i}" if i else destination)
        except OSError as ex:
            i+=1
            print(ex)

It will keep trying to move the files until operation passes successfully. Just a warning, it will add numbers AFTER the file extension, so the files won't be properly recognized by their extension. But that's an excercise I'm leaving for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文