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