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))