【发布时间】: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