简单文件管理系统实现
时间: 2023-12-18 17:03:35 浏览: 61
一个简单的文件管理系统可以包括以下功能:
1. 创建文件夹和文件
2. 删除文件夹和文件
3. 查看文件夹和文件列表
4. 重命名文件和文件夹
5. 移动文件和文件夹
下面是一个简单的文件管理系统的实现:
1. 创建文件夹和文件
```
import os
path = 'C:/Users/username/Desktop/test'
# 创建文件夹
folder_name = 'folder1'
folder_path = os.path.join(path, folder_name)
if not os.path.exists(folder_path):
os.makedirs(folder_path)
# 创建文件
file_name = 'file1.txt'
file_path = os.path.join(folder_path, file_name)
if not os.path.exists(file_path):
with open(file_path, 'w') as f:
f.write('Hello, world!')
```
2. 删除文件夹和文件
```
import os
path = 'C:/Users/username/Desktop/test'
# 删除文件
file_path = os.path.join(path, 'file1.txt')
if os.path.exists(file_path):
os.remove(file_path)
# 删除文件夹
folder_path = os.path.join(path, 'folder1')
if os.path.exists(folder_path):
os.rmdir(folder_path)
```
3. 查看文件夹和文件列表
```
import os
path = 'C:/Users/username/Desktop/test'
# 查看文件夹列表
folders = [f for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))]
print(folders)
# 查看文件列表
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
print(files)
```
4. 重命名文件和文件夹
```
import os
path = 'C:/Users/username/Desktop/test'
# 重命名文件
old_file_path = os.path.join(path, 'file1.txt')
new_file_name = 'file2.txt'
new_file_path = os.path.join(path, new_file_name)
if os.path.exists(old_file_path):
os.rename(old_file_path, new_file_path)
# 重命名文件夹
old_folder_path = os.path.join(path, 'folder1')
new_folder_name = 'folder2'
new_folder_path = os.path.join(path, new_folder_name)
if os.path.exists(old_folder_path):
os.rename(old_folder_path, new_folder_path)
```
5. 移动文件和文件夹
```
import os
path = 'C:/Users/username/Desktop/test'
# 移动文件
file_path = os.path.join(path, 'file2.txt')
new_folder_path = os.path.join(path, 'folder2')
if os.path.exists(file_path):
os.replace(file_path, os.path.join(new_folder_path, os.path.basename(file_path)))
# 移动文件夹
folder_path = os.path.join(path, 'folder2')
new_path = 'C:/Users/username/Desktop/test2'
if os.path.exists(folder_path):
os.replace(folder_path, os.path.join(new_path, os.path.basename(folder_path)))
```
阅读全文