PythonStudy——跨文件夹移动文件

本文介绍了一种使用Python进行跨文件夹移动文件的方法,通过定义move_file函数,检查源文件是否存在并读取,然后在目标文件夹创建或确认其存在,并将文件内容写入新位置,最后删除原文件,实现了文件的有效迁移。

跨文件夹移动文件

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值