Python根据操作系统自动调用创建文件目录小脚本


     工作中经常碰到这种情况:脚本开发是在本地(Windows),然后等脚本写好测好后放到生产服务器(Linux)。这就涉及到脚本在两种操作系统上的迁移和文件目录使用问题。以下小脚本虽然简单但还是很实用的。

import os
import platform


def doc_path():
    if platform.system() == "Linux":
        if os.path.exists("/root/"):
            pass
        else:
            os.makedirs("/root/")
        return "/root/"
    elif platform.system() == "Windows":
        if os.path.exists("D:/script/"):
            pass
        else:
            os.makedirs("D:/script/")
        return "D:/script/"
    else:
        exit()


     当然,也可以再详细一点,来一个加强版!


import os
import platform


def route(spe):
    spe = str(spe)
    if platform.system() == "Linux":
        if spe[0] == '/':
            if os.path.exists(spe):
                pass
            else:
                os.makedirs(spe)
        elif not (spe[0] == '/'):
            spe = '/' + spe
            if os.path.exists(spe):
                pass
            else:
                os.makedirs(spe)
        else:
            exit()
        return spe
    elif platform.system() == "Windows":
        if spe[1] == ':':
            if os.path.exists(spe):
                pass
            else:
                os.makedirs(spe)
        elif not (spe[1] == ':'):
            spe = "D:\\" + spe
            if os.path.exists(spe):
                pass
            else:
                os.makedirs(spe)
        else:
            exit()
        return spe
    else:
        exit()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值