python保持原有文件名称不变的基础上顺位排序
时间: 2024-08-13 22:09:48 浏览: 62
在Python中,如果你想按照某种规则(比如文件修改时间、创建时间等)对文件进行排序,并保持原有的文件名不变,但将它们移动到一个新的目录下,你可以使用`shutil`和`os`模块中的功能。首先,你需要遍历源目录,然后根据指定的关键字排序,最后复制文件到目标目录。
以下是一个简单的例子,假设我们按文件的创建时间排序:
```python
import os
import shutil
from datetime import datetime
def sort_files(src_dir, dst_dir):
# 检查并创建目标目录
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
# 获取源目录下的所有文件
for filename in os.listdir(src_dir):
src_file = os.path.join(src_dir, filename)
dst_file = os.path.join(dst_dir, filename) # 维持原始文件名
# 如果是文件,获取创建时间并排序
if os.path.isfile(src_file):
file_time = datetime.fromtimestamp(os.path.getctime(src_file))
dst_sorted_file = os.path.join(dst_dir, f"{file_time.strftime('%Y%m%d%H%M%S')}-{filename}")
# 将文件复制到新的位置,保留原名并添加时间戳后缀
shutil.copy2(src_file, dst_sorted_file)
# 使用函数,传入源目录和目标目录作为参数
sort_files('/path/to/source', '/path/to/destination')
```
在这个脚本中,`datetime.fromtimestamp()`用于获取文件的创建时间,然后使用`strftime()`格式化为字符串以便于添加到新文件名中。`shutil.copy2()`则负责安全地复制文件,同时保持元数据。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)