python如何把txt文件移入指定文件夹,若txt文件同名则覆盖原txt文件
时间: 2023-06-14 20:03:11 浏览: 107
你可以使用Python中的`shutil`模块来实现这个功能。具体步骤如下:
1. 导入`shutil`模块:`import shutil`
2. 使用`shutil.move(src_file, dst_folder)`方法将txt文件移动到指定文件夹中。其中,`src_file`是txt文件的路径,`dst_folder`是目标文件夹的路径。
3. 如果目标文件夹中已经存在同名的txt文件,可以使用`shutil.copy2(src_file, dst_file)`方法覆盖原文件。其中,`src_file`是txt文件的路径,`dst_file`是目标文件夹中同名txt文件的路径。
示例代码如下:
```python
import os
import shutil
# txt文件路径
src_file = 'test.txt'
# 目标文件夹路径
dst_folder = 'target_folder'
# 判断目标文件夹是否存在,如果不存在则创建
if not os.path.exists(dst_folder):
os.makedirs(dst_folder)
# 移动txt文件到目标文件夹
shutil.move(src_file, dst_folder)
# 如果目标文件夹中已经存在同名txt文件,则覆盖原文件
dst_file = os.path.join(dst_folder, os.path.basename(src_file))
if os.path.exists(dst_file):
shutil.copy2(src_file, dst_file)
```
阅读全文
相关推荐














