簡體   English   中英

Python 類中的可選參數

[英]Optional Parameters in Classes in Python

這是我的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()
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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM