python3: os_phone.py针对手机目录及文件操作的几个常用功能的简单封装

os模块是Python标准库中的一个用于访问操作系统相关功能的模块。

os模块的主要功能:系统相关、目录及文件操作、执行命令和管理进程

特别是其中对于目录及文件的操作非常的方便,但是并不能对android手机的目录进行操作,罗列了一下,对于目录的操作,以下功能是通用的. 

os.path.split()/os.path.splitext是可以通用的.

但以下四个常用功能并不适用,需要重写:

listdir()/isdir()/isfile()/isexists()

import subprocess
import os

curpath = '/sdcard/'


# 返回指定目录的文件列表
def listdir(path = curpath):
    cmd = 'adb shell ls ' + path
    list_dir = subprocess.run(cmd, capture_output=True, encoding='utf-8', shell=True).stdout.strip().split('\n')
    return  list_dir


# 判断path所指是否为folder
def isdir(path):
    cmd = 'adb shell cd ' + path
    if subprocess.run(cmd, capture_output=True, encoding='utf-8', shell=True).stderr == '':
        return True
    else:
        return False


# 判断path所指是否为file
def isfile(path):
    cmd = 'adb shell ls ' + path
    temp = subprocess.run(cmd, capture_output=True, encoding='utf-8', shell=True)
    if temp.stdout.strip() == path.strip():
        return True
    else:
        return False


# 判断路径或文件在当前工作目录下是否存在
def isexists(path): 
    if isdir(path):
        return True
    elif isfile(path):
        return True
    else:
        return False


if __name__ == '__main__':
    path1 = '/sdcard/0000'
    path2 = '/sdcard/shumei.txt'
    print(isdir(path1))
    print(isfile(path1))
    print(isexists(path2))
    print(os.path.split(path2))
    print(os.path.splitext(path2))

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值