Python 项目:基于命令行的文件管理器

这个项目是一个基于 Python 编写的命令行文件管理器,能够帮助用户执行一些常见的文件操作,例如:创建文件夹、删除文件、列出文件夹中的文件、复制文件、移动文件等。它使用了 Python 的 osshutil 库,能够快速管理本地文件系统。


代码

import os
import shutil

class FileManager:
    def __init__(self, base_path='.'):
        self.base_path = base_path

    def create_directory(self, dir_name):
        try:
            os.makedirs(os.path.join(self.base_path, dir_name))
            print(f"目录 '{dir_name}' 创建成功!")
        except FileExistsError:
            print(f"目录 '{dir_name}' 已经存在!")
        except Exception as e:
            print(f"创建目录时发生错误: {e}")

    def delete_file(self, file_name):
        try:
            file_path = os.path.join(self.base_path, file_name)
            if os.path.exists(file_path):
                os.remove(file_path)
                print(f"文件 '{file_name}' 删除成功!")
            else:
                print(f"文件 '{file_name}' 不存在!")
        except Exception as e:
            print(f"删除文件时发生错误: {e}")

    def list_files(self):
        try:
            files = os.listdir(self.base_path)
            if files:
                print("当前目录中的文件:")
                for file in files:
                    print(f"- {file}")
            else:
                print("当前目录中没有文件。")
        except Exception as e:
            print(f"列出文件时发生错误: {e}")

    def copy_file(self, src_file, dest_file):
        try:
            src_path = os.path.join(self.base_path, src_file)
            dest_path = os.path.join(self.base_path, dest_file)
            if os.path.exists(src_path):
                shutil.copy(src_path, dest_path)
                print(f"文件 '{src_file}' 已复制到 '{dest_file}'")
            else:
                print(f"源文件 '{src_file}' 不存在!")
        except Exception as e:
            print(f"复制文件时发生错误: {e}")

    def move_file(self, src_file, dest_file):
        try:
            src_path = os.path.join(self.base_path, src_file)
            dest_path = os.path.join(self.base_path, dest_file)
            if os.path.exists(src_path):
                shutil.move(src_path, dest_path)
                print(f"文件 '{src_file}' 已移动到 '{dest_file}'")
            else:
                print(f"源文件 '{src_file}' 不存在!")
        except Exception as e:
            print(f"移动文件时发生错误: {e}")

    def rename_file(self, old_name, new_name):
        try:
            old_path = os.path.join(self.base_path, old_name)
            new_path = os.path.join(self.base_path, new_name)
            if os.path.exists(old_path):
                os.rename(old_path, new_path)
                print(f"文件 '{old_name}' 已重命名为 '{new_name}'")
            else:
                print(f"文件 '{old_name}' 不存在!")
        except Exception as e:
            print(f"重命名文件时发生错误: {e}")

# 使用示例
if __name__ == '__main__':
    manager = FileManager()

    # 创建文件夹
    manager.create_directory("test_folder")

    # 列出当前文件夹中的文件
    manager.list_files()

    # 创建一些测试文件
    with open('test1.txt', 'w') as f:
        f.write("Hello World!")
    
    with open('test2.txt', 'w') as f:
        f.write("Python File Manager!")

    # 列出文件
    manager.list_files()

    # 复制文件
    manager.copy_file('test1.txt', 'copy_of_test1.txt')

    # 移动文件
    manager.move_file('test2.txt', 'moved_test2.txt')

    # 删除文件
    manager.delete_file('test1.txt')
    manager.delete_file('copy_of_test1.txt')
    manager.delete_file('moved_test2.txt')

    # 重命名文件
    manager.rename_file('test2.txt', 'renamed_test2.txt')

使用说明

  1. 安装和运行环境

    • 你需要安装 Python 3.x 版本。你可以通过以下命令确认你的 Python 版本:
      python --version
      
    • 将上面的代码保存为 file_manager.py 文件。
  2. 功能概述
    这个文件管理器提供了如下功能:

    • create_directory(dir_name):创建一个新的文件夹。
    • delete_file(file_name):删除指定的文件。
    • list_files():列出当前目录下的文件。
    • copy_file(src_file, dest_file):复制文件到新的位置。
    • move_file(src_file, dest_file):移动文件到新的位置。
    • rename_file(old_name, new_name):重命名指定的文件。
  3. 操作说明

    • 创建文件夹:可以通过 create_directory 方法创建新的目录。例如,manager.create_directory("test_folder") 会在当前目录下创建一个名为 test_folder 的文件夹。
    • 删除文件:通过 delete_file 删除指定的文件。例如,manager.delete_file("test1.txt") 会删除 test1.txt 文件。
    • 列出文件:使用 list_files 可以查看当前目录下的所有文件。
    • 复制文件:使用 copy_file("src", "dest") 可以复制一个文件到新的位置。
    • 移动文件:使用 move_file("src", "dest") 来移动文件。
    • 重命名文件:通过 rename_file("old_name", "new_name") 进行文件重命名。
  4. 错误处理

    • 如果执行任何操作时出现问题(例如,文件不存在),程序会输出相应的错误信息。
  5. 使用示例

    • 运行脚本后,会自动执行一系列文件操作(如创建文件夹、创建文件、复制、删除等),可以根据自己的需求修改这些操作。

总结

这个项目展示了如何使用 Python 创建一个简单的命令行文件管理器,适用于日常的文件管理任务。用户可以轻松创建、删除、复制、移动、列出和重命名文件,具有较高的实用性,且通过模块化设计,易于扩展其他功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值