# 小型项目示例：文件处理工具

URL: https://caijiao.org/python/ch11/project-filetool
Source: docs/python/ch11/project-filetool.md
Description: 本章将通过一个简单的文件处理工具示例，展示如何使用 Python 编写一个工具，涵盖文件读取、写入、复制、删除等基本文件操作。

在本章中，我们将编写一个文件处理工具，用户可以通过该工具进行常见的文件操作，例如读取文件内容、写入文件、复制文件以及删除文件。我们将运用 [Python](/python/) 的文件操作和用户输入输出功能，来实现这个简单的文件管理工具。

## 项目目标

1. 读取指定文件并显示其内容。
2. 将用户输入的内容写入指定文件。
3. 复制文件到指定位置。
4. 删除指定的文件。
5. 提供简单的菜单供用户选择操作。

## 项目结构

```

file\_tool/
│
├── file\_tool.py       # 主程序，处理文件操作
├── README.md          # 项目说明
└── sample.txt         # 示例文件，供测试使用

```

## 代码实现

### 1. 创建 `file_tool.py` 文件

```python
# file_tool.py

import os
import shutil

# 显示文件内容
def read_file(file_path):
    if not os.path.exists(file_path):
        print("文件不存在！")
        return
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
        print("文件内容：")
        print(content)

# 写入内容到文件
def write_file(file_path):
    content = input("请输入要写入的内容：\n")
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(content)
    print("内容已写入文件。")

# 复制文件
def copy_file(source_path, dest_path):
    if not os.path.exists(source_path):
        print("源文件不存在！")
        return
    shutil.copy(source_path, dest_path)
    print(f"文件已从 {source_path} 复制到 {dest_path}")

# 删除文件
def delete_file(file_path):
    if os.path.exists(file_path):
        os.remove(file_path)
        print(f"文件 {file_path} 已删除。")
    else:
        print("文件不存在，无法删除。")

# 显示菜单
def display_menu():
    print("\n--- 文件处理工具 ---")
    print("1. 读取文件")
    print("2. 写入文件")
    print("3. 复制文件")
    print("4. 删除文件")
    print("5. 退出")
    choice = input("请选择操作: ")
    return choice

# 主程序
def main():
    while True:
        choice = display_menu()
        if choice == '1':
            file_path = input("请输入要读取的文件路径: ")
            read_file(file_path)
        elif choice == '2':
            file_path = input("请输入要写入的文件路径: ")
            write_file(file_path)
        elif choice == '3':
            source_path = input("请输入源文件路径: ")
            dest_path = input("请输入目标文件路径: ")
            copy_file(source_path, dest_path)
        elif choice == '4':
            file_path = input("请输入要删除的文件路径: ")
            delete_file(file_path)
        elif choice == '5':
            print("感谢使用文件处理工具！")
            break
        else:
            print("无效选择，请重新输入。")

if __name__ == '__main__':
    main()
```

### 2. 示例文件 `sample.txt`

在项目文件夹中创建一个名为 `sample.txt` 的文件，用于测试文件处理工具。文件内容可以是简单的文本：

```
这是一个示例文件。
你可以通过文件处理工具进行操作。
```

### 3. 如何运行

- 将上述代码保存为 `file_tool.py` 文件。
- 在命令行中运行以下命令：

```bash
python file_tool.py
```

### 4. 功能说明

#### 读取文件

当用户选择读取文件时，程序会要求输入文件的路径，程序会读取文件内容并打印在屏幕上。

#### 写入文件

当用户选择写入文件时，程序会要求用户输入文件路径以及要写入的内容，程序将内容写入指定的文件中。

#### 复制文件

当用户选择复制文件时，程序会要求输入源文件路径和目标文件路径，然后将源文件复制到目标位置。

#### 删除文件

当用户选择删除文件时，程序会要求输入文件路径，并删除该文件。

#### 退出程序

用户可以选择退出程序，程序将结束。

## 项目扩展

本项目是一个简单的文件处理工具，适合初学者练习。随着需求的变化，我们可以对项目进行扩展：

- 增加对目录的操作，例如创建目录、删除目录等。
- 支持文件类型的过滤，例如只操作文本文件。
- 提供批量文件操作，例如批量复制或批量删除文件。
- 支持更复杂的文件内容处理，例如查找和替换文本。

通过这个文件处理工具，你可以学会如何使用 Python 进行文件操作，包括读取、写入、复制和删除文件等常见任务。
