欢迎访问宙启技术站
智能推送

使用Python编写一个简单的文件管理工具

发布时间:2023-12-04 12:38:56

下面是使用Python编写的一个简单文件管理工具的例子:

import os
import shutil

def create_directory(path):
    if not os.path.exists(path):
        os.makedirs(path)
        print(f"创建目录 {path} 成功")
    else:
        print(f"目录 {path} 已存在")

def delete_directory(path):
    if os.path.exists(path):
        shutil.rmtree(path)
        print(f"删除目录 {path} 成功")
    else:
        print(f"目录 {path} 不存在")

def list_directory_files(path):
    if os.path.exists(path):
        print(f"目录 {path} 中的文件:")
        for file in os.listdir(path):
            print(file)
    else:
        print(f"目录 {path} 不存在")

def copy_file(source, destination):
    if os.path.isfile(source):
        shutil.copy2(source, destination)
        print(f"复制文件 {source} 到 {destination} 成功")
    else:
        print(f"文件 {source} 不存在")

def move_file(source, destination):
    if os.path.isfile(source):
        shutil.move(source, destination)
        print(f"移动文件 {source} 到 {destination} 成功")
    else:
        print(f"文件 {source} 不存在")

def delete_file(path):
    if os.path.isfile(path):
        os.remove(path)
        print(f"删除文件 {path} 成功")
    else:
        print(f"文件 {path} 不存在")

# 创建一个目录
create_directory("test_dir")

# 列出目录中的文件
list_directory_files("test_dir")

# 创建一个文件
file_path = os.path.join("test_dir", "test_file.txt")
with open(file_path, "w") as file:
    file.write("这是一个测试文件")
print(f"已创建文件 {file_path}")

# 复制文件
copy_file(file_path, "test_dir_copy/test_file.txt")

# 列出目录中的文件
list_directory_files("test_dir_copy")

# 移动文件
move_file(file_path, "test_dir_copy/test_file.txt")

# 删除目录
delete_directory("test_dir")

# 删除文件
delete_file("test_dir_copy/test_file.txt")

上述代码中,我们定义了一些基本的文件管理函数,包括创建目录、删除目录、列出目录中的文件、复制文件、移动文件和删除文件。我们以一个简单的使用例子来说明每个函数的用法,首先创建一个名为test_dir的目录,然后列出该目录中的文件,再创建一个名为test_file.txt的文件,接着复制该文件到test_dir_copy目录,然后再次列出test_dir_copy目录中的文件,然后将文件移动到test_dir_copy目录,最后删除创建的目录和文件。

以上就是一个简单的文件管理工具的例子。你可以根据自己的需求来扩展这个工具,添加更多的功能和操作。