这是我的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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句