python将文件夹里的文件打乱,并将打乱顺序的文件保存在原文件夹中
时间: 2023-06-13 19:03:09 浏览: 124
可以使用`os`和`random`模块来实现文件夹里的文件打乱,并将打乱顺序的文件保存在原文件夹中。具体步骤如下:
1. 导入所需模块:
```python
import os
import random
```
2. 获取文件夹中的所有文件:
```python
folder_path = '文件夹路径'
file_list = os.listdir(folder_path)
```
3. 打乱文件顺序:
```python
random.shuffle(file_list)
```
4. 重命名并保存打乱顺序的文件:
```python
for i, file_name in enumerate(file_list):
# 获取原文件路径和新文件路径
old_path = os.path.join(folder_path, file_name)
new_name = f'{i+1}_{file_name}'
new_path = os.path.join(folder_path, new_name)
# 重命名并保存文件
os.rename(old_path, new_path)
```
完整代码如下:
```python
import os
import random
folder_path = '文件夹路径'
file_list = os.listdir(folder_path)
random.shuffle(file_list)
for i, file_name in enumerate(file_list):
old_path = os.path.join(folder_path, file_name)
new_name = f'{i+1}_{file_name}'
new_path = os.path.join(folder_path, new_name)
os.rename(old_path, new_path)
```
注意:运行前请将`folder_path`替换成实际的文件夹路径。
阅读全文
相关推荐


















