要求:编写一个简单的文件管理器程序,让用户可以浏览电脑上的文件和文件夹。用户可以进行创建、复制、剪切、粘贴和删除操作
以下是一个简单的文件管理器程序的Python代码实现,用于浏览、创建、复制、剪切、粘贴和删除文件和文件夹:
import os
import shutil
while True:
# 显示当前目录下的文件和文件夹
print('当前目录:', os.getcwd())
print('目录列表:', os.listdir())
# 获取用户输入的命令
command = input('请输入命令(1-查看文件,2-创建文件夹,3-复制文件/文件夹,4-剪切文件/文件夹,5-粘贴文件/文件夹,6-删除文件/文件夹,7-退出):')
# 查看文件
if command == '1':
filename = input('请输入要查看的文件名:')
if os.path.isfile(filename):
with open(filename, 'r') as f:
print(f.read())
else:
print('该文件不存在。')
# 创建文件夹
elif command == '2':
dirname = input('请输入要创建的文件夹名称:')
os.mkdir(dirname)
# 复制文件/文件夹
elif command == '3':
source = input('请输入要复制的文件/文件夹路径:')
destination = input('请输入目标路径:')
if os.path.isfile(source):
shutil.copy(source, destination)
else:
shutil.copytree(source, destination)
# 剪切文件/文件夹
elif command == '4':
source = input('请输入要剪切的文件/文件夹路径:')
destination = input('请输入目标路径:')
shutil.move(source, destination)
# 粘贴文件/文件夹
elif command == '5':
source = input('请输入要粘贴的文件/文件夹路径:')
destination = os.getcwd()
if os.path.isfile(source):
shutil.copy(source, destination)
else:
shutil.copytree(source, os.path.join(destination, os.path.basename(source))))
# 删除文件/文件夹
elif command == '6':
filename = input('请输入要删除的文件/文件夹名称:')
if os.path.isfile(filename):
os.remove(filename)
else:
shutil.rmtree(filename)
# 退出程序
elif command == '7':
break
# 命令输入错误
else:
print('命令输入错误。')
该程序使用了Python自带的os和shutil模块,可以在终端中运行,实现简单的文件管理功能。需要注意的是,在复制和粘贴文件/文件夹时,如果目标路径不存在,需要提前创建该目录。