python实现 mv 移动文件时,目标路径下已存在同名文件不覆盖同名目标文件
时间: 2024-05-03 20:18:16 浏览: 15
在 Python 中,可以使用 shutil 库的 move 函数来实现文件移动。如果目标路径下已存在同名文件,可以使用 os.path.exists 函数来判断是否存在同名文件,如果存在则可以在文件名后面添加一个时间戳或者随机数,避免覆盖同名目标文件。
以下是一个示例代码:
```python
import shutil
import os
import time
def move_file(src_path, dst_path):
filename = os.path.basename(src_path)
dst_file_path = os.path.join(dst_path, filename)
if os.path.exists(dst_file_path):
timestamp = time.strftime('%Y%m%d%H%M%S', time.localtime())
name, ext = os.path.splitext(filename)
dst_file_path = os.path.join(dst_path, '{}_{}{}'.format(name, timestamp, ext))
shutil.move(src_path, dst_file_path)
```
在上面的代码中,首先通过 os.path.basename 函数获取源文件名,然后通过 os.path.join 函数拼接目标文件路径。接着使用 os.path.exists 函数判断是否存在同名文件,如果存在则在文件名后面添加一个时间戳,并重新拼接目标文件路径。最后使用 shutil.move 函数将文件移动到目标路径下。