【问题标题】:Renaming and moving files with specific file extension重命名和移动具有特定文件扩展名的文件
【发布时间】:2020-09-20 14:34:08
【问题描述】:

这是我执行文件操作的代码,例如移动、重命名、删除具有特定文件扩展名的批量文件

import os


class OperationsOnFiles:
    def __init__(self, src_path):
        self.src_path = src_path

    # Prints the name of all the files with the extensions in the folder specified
    def src_files(self):
        print("All the files in the source folder are: ")
        print()
        i = 1
        for file in os.listdir(self.src_path):
            print(str(i) + ". " + file)
            i += 1
        return ""

    # Renames all the files or files with specific extension in the folder with a number attached to the end of the file name
    def rename_bulk_files(self):
        i = 0
        file_path = self.src_path
        for file in os.listdir(file_path):
            dot_index = file.index('.')
            if not files_extension or file_path.endswith(files_extension):
                file_src = os.path.join(file_path, file)
                file_des = os.path.join(file_path, file[0:dot_index] + "_" + str(i) + file[dot_index:])
                os.rename(file_src, file_des)
                i += 1

        print("All files have been renamed")

    # Move files or files with specific extension in one folder to another folder
    def move_bulk_files(self):
        file_path = self.src_path
        destination_folder_path = input("Enter the destination folder in which you want to move the files: ")
        for file in os.listdir(file_path):
            if not files_extension or file_path.endswith(files_extension):
                src_path = os.path.join(file_path, file)
                des_path = os.path.join(destination_folder_path, file)
                os.replace(src_path, des_path)
        print("All files have been moved to the destination folder")

    # Delete files or files with specific extensions in a folder
    def delete_bulk_files(self):
        path = self.src_path
        for i in os.listdir(self.src_path):
            file_path = os.path.join(path, i)
            if not files_extension or file_path.endswith(files_extension):
                os.remove(file_path)
        print("All files have been deleted")


source_folder_path = input("Enter the source of the folder on which you wish to perform the operation: ")
my_operations = OperationsOnFiles(source_folder_path)
print("File Operations: \n1. Rename Bulk Files \n2. Move Bulk Files \n3. Delete Bulk Files")
user_choice = int(input("Enter a number to perform the operations: "))
files_extension = input("Enter file extension of the file to be deleted or press 'ENTER' to delete all files: ").lower()
if user_choice == 1:
    my_operations.rename_bulk_files()
elif user_choice == 2:
    my_operations.move_bulk_files()
elif user_choice == 3:
    my_operations.delete_bulk_files()
else:
    print("Please enter a valid input")

在函数 rename_bulk_files 和 move_bulk_files 中,当我键入特定的扩展名时,函数块不起作用,但它对 delete_bulk_files 函数起作用。我对前一个函数使用了与后一个函数相同的逻辑,但它不起作用。

我想在 rename_bulk_files 和 move_bulk_files 中传递 *files_extensions 以便您可以指定多个文件扩展名,用逗号分隔。因此,如果您输入 .pdf、.mp4、.docx,所有具有这些扩展名的文件都将被重命名或移动。但我似乎也做不到。

【问题讨论】:

  • 尝试将 files_extension 变量传递给函数。

标签: python function file class operating-system


【解决方案1】:

您在函数之间错误地处理了文件路径。

在删除函数中,您根据目录路径定义单个文件路径。

def delete_bulk_files(self):
    path = self.src_path
    for i in os.listdir(self.src_path):
        file_path = os.path.join(path, i)
        if not files_extension or file_path.endswith(files_extension):
            os.remove(file_path)
    print("All files have been deleted")

你忘了在其他函数中这样做

def move_bulk_files(self):
    file_path = self.src_path
    destination_folder_path = input("Enter the destination folder in which you want to move the files: ")
    for file in os.listdir(file_path):
        if not files_extension or file_path.endswith(files_extension):
            src_path = os.path.join(file_path, file)
            des_path = os.path.join(destination_folder_path, file)
            os.replace(src_path, des_path)
    print("All files have been moved to the destination folder")

因此,代码不会执行(除非输入为空且 files_extension 为 False)。

所以只需添加额外的行来调整其他功能中的路径

file_path = os.path.join(path, i)

之后它应该会按预期工作。

除了您的问题之外还有其他一些事情

您应该改进代码中的变量命名。例如,如果您根据用户输入在 init 函数中定义 self.path 变量,则无需在类的子函数中声明变量 path=self.path,只需替换它直接使用 self.path,这将增加代码的可读性。

此外,据我所知 os.replace 无法处理不同磁盘之间的移动。因此,您应该考虑将这一职责转移到 shutil.move() 函数。

一般来说,您还应该考虑将使用提示打包到您的课程中。在这一点上,您的程序的关键缺点是整个程序在一次操作后关闭,需要重新启动。这样您就可以在功能方面遥遥领先!

编辑 下面的代码在我的系统上按预期工作。我已经用“!”评论了相应的行。虽然我真的希望你现在自己弄清楚了。这是一个非常简单的语法错误。

import os


class OperationsOnFiles:
    def __init__(self, src_path):
        self.src_path = src_path

    # Prints the name of all the files with the extensions in the folder specified
    def src_files(self):
        print("All the files in the source folder are: ")
        print()
        i = 1
        for file in os.listdir(self.src_path):
            print(str(i) + ". " + file)
            i += 1
        return ""

    # Renames all the files or files with specific extension in the folder with a number attached to the end of the file name
    def rename_bulk_files(self):
        i = 0
        path = self.src_path
        for file in os.listdir(path):
            dot_index = file.index('.')
            #file_path = os.path.join(path, file)
            if not files_extension or file.endswith(files_extension):  # !
                file_src = os.path.join(path, file)  # !
                file_des = os.path.join(path, file[0:dot_index] + "_" + str(i) + file[dot_index:])
                os.rename(file_src, file_des)
                i += 1

        print("All files have been renamed")

    # Move files or files with specific extension in one folder to another folder
    def move_bulk_files(self):
        path = self.src_path
        destination_folder_path = input("Enter the destination folder in which you want to move the files: ")
        for file in os.listdir(path):
            #file_path = os.path.join(path, file)
            if not files_extension or file.endswith(files_extension):  # !
                src_path = os.path.join(path, file)  # !
                des_path = os.path.join(destination_folder_path, file)
                os.replace(src_path, des_path)
        print("All files have been moved to the destination folder")

    # Delete files or files with specific extensions in a folder
    def delete_bulk_files(self):
        path = self.src_path
        for i in os.listdir(self.src_path):
            file_path = os.path.join(path, i)
            if not files_extension or file_path.endswith(files_extension):
                os.remove(file_path)
        print("All files have been deleted")


source_folder_path = input("Enter the source of the folder on which you wish to perform the operation: ")
my_operations = OperationsOnFiles(source_folder_path)
print("File Operations: \n1. Rename Bulk Files \n2. Move Bulk Files \n3. Delete Bulk Files")
user_choice = int(input("Enter a number to perform the operations: "))
files_extension = input("Enter file extension of the file to be deleted or press 'ENTER' to delete all files: ").lower()
if user_choice == 1:
    my_operations.rename_bulk_files()
elif user_choice == 2:
    my_operations.move_bulk_files()
elif user_choice == 3:
    my_operations.delete_bulk_files()
else:
    print("Please enter a valid input")

【讨论】:

  • 我想你没有完全纠正它。如果您添加行 file_path = os.path.join(path, i) 自然您必须根据您的变量名称进行更正。我没有假设我必须自己调试和重写您的代码,而是给您提示自己做。因此,您要么添加完整路径的行,要么直接根据 for 循环处理文件(而不是 file_path)。
  • 谢谢,伙计!现在我意识到我犯的错误。我没有正确调试代码,否则我会更正它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-31
  • 1970-01-01
  • 2020-04-05
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
  • 2016-07-26
相关资源
最近更新 更多