【问题标题】:Optional Parameters in Classes in PythonPython 类中的可选参数
【发布时间】:2020-09-20 10:36:20
【问题描述】:

这是我的 python 代码,用于执行删除、移动和重命名多个文件等操作。此代码适用于所有类型的文件。假设我想添加一个可选参数,例如删除带有“.pdf”扩展名的文件,我该如何添加该选项?好像不是强制添加,但是如果你通过了,所有的pdf文件都会被删除。

我只想添加一个可选参数,当它被传递时,只对那些文件执行操作

import os


class FileOperation:
    def __init__(self, file_loc):
        self.file_loc = file_loc

    def file_location(self):
        print("Source folder contents: ")
        print()
        for i in os.listdir(self.file_loc):
            print(i)
        print()

    def rename_bulk_files(self):
        c = 0
        path = self.file_loc
        for i in os.listdir(self.file_loc):
            dot_index = i.index('.')
            src = os.path.join(path, i)
            dst = os.path.join(path, i[0:dot_index] + "_" + str(c) + i[dot_index:])
            os.rename(src, dst)
            c += 1
        return "Renaming of files has finished"

    def delete_bulk_files(self):
        path = self.file_loc
        for i in os.listdir(self.file_loc):
            file_path = os.path.join(path, i)
            os.remove(file_path)
        print("All files have been deleted")

    def move_bulk_files(self):
        path = self.file_loc
        destination_folder = input("Enter the destination folder / folders separated by a comma: ")
        for i in os.listdir(self.file_loc):
            src_path = os.path.join(path, i)
            des_path = os.path.join(destination_folder, i)
            os.replace(src_path, des_path)
        print("All files have been moved to the destination folder")


source_folder = input("Enter source folder/ folders locations separated by a comma: ")


my_file_operations = FileOperation(source_folder)
my_file_operations.delete_bulk_files()

【问题讨论】:

    标签: python file class operating-system


    【解决方案1】:
    files_extension = input(“Enter files extension (defaults to all files if not provided): “)
    

    然后在delete_bulk_files :

    
    file_path = os.path.join(path, i)
    if not files_extension or file_path.endswith(files_extension):
      os.remove(file_path)
    

    【讨论】:

    • 即使这样有效,如果我没有在 file_extension 中输入任何内容,默认情况下所有文件都应该被删除
    • 正确,如果不提供扩展名点击回车应该会删除所有文件
    猜你喜欢
    • 2018-11-16
    • 2015-07-14
    • 2018-10-28
    • 2019-07-12
    • 2023-03-21
    • 2010-12-07
    • 2012-05-02
    • 1970-01-01
    • 2020-02-07
    相关资源
    最近更新 更多