import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(BASE_DIR)
def move_file(file, folder):
if not (os.path.exists(file) and os.path.isfile(file)):
print('文件不存在或非法')
return False
if not os.path.exists(folder):
os.makedirs(folder)
file_name = os.path.split(file)[1]
# file_name = os.path.basename(file)
new_file = os.path.join(folder, file_name)
with open(file, 'rb') as rf, open(new_file, 'wb') as wf:
for line in rf:
wf.write(line)
os.remove(file)
# 将目标文件夹下的目标文件移动到指定文件夹下
file = os.path.join(BASE_DIR, 'part5', 'mm.py')
folder = os.path.join(BASE_DIR, 'part6', 'abc')
move_file(file, folder)
转载于:https://www.cnblogs.com/tingguoguoyo/p/10834404.html
本文介绍了一种使用Python进行跨文件夹移动文件的方法,通过定义move_file函数,检查源文件是否存在并读取,然后在目标文件夹创建或确认其存在,并将文件内容写入新位置,最后删除原文件,实现了文件的有效迁移。
3388

被折叠的 条评论
为什么被折叠?



