Python基础应用整理

初学Python,函数整理。

1.获取python脚本启动时命令行传参的个数

def getArgvNum():
    argvNum = 0
    for myArgv in sys.argv:
        argvNum += 1
    return argvNum - 1

2.获取文件扩展名

def getExpandedName(srcName):
    ret = os.path.splitext(srcName)[-1]
    return ret

3.删除文件扩展名(获取路径)

def delExpandedName(srcName):
    while srcName[-1] != '.':
        srcName = srcName[:-1]
    srcName = srcName[:-1]
    return srcName

4.按行读取文件,并返回行列表

def readLineToList(DaemonLog):
    lineList = []
    while 1:
        line = DaemonLog.readline()
        if line:
            lineList.append(line)
        else:
            break
    return lineList

5.递归删除非空目录

def removeDir(dir):
    dir = dir.replace('\\', '/')
    if(os.path.isdir(dir)):
        for p in os.listdir(dir):
            removeDir(os.path.join(dir,p))
        if(os.path.exists(dir)):
            os.rmdir(dir)
    else:
        if(os.path.exists(dir)):
            os.remove(dir)

6.将zip压缩包解压到指定目录

def UnZipLogFile(zipFile,unZipDir):
    inputFile = zipFile  # 待解压的文件
    UnZipDir = unZipDir  # 解压后存放的目录
    isZip = zipfile.is_zipfile(inputFile)
    if isZip:
        fz = zipfile.ZipFile(inputFile, 'r')
        for file in fz.namelist():
            # print(file)  # 打印zip归档中目录
            fz.extract(file, UnZipDir)  # 将文件解压到指定目录中
        return True
    else:
        return False

7.统计路径path下的文件个数

def dirCnt(path):
    count = 0
    for fn in os.listdir(path):
        count = count + 1
    return count

8.遍历指定路径下的文件,返回该路径下的非目录文件list

def traverseDir3(file):
    fileList = []
    fs = os.listdir(file)
    for file1 in fs:
        tmp_path = os.path.join(file, file1)
        if not os.path.isdir(tmp_path):
            fileList.append(tmp_path)
    return fileList

9.获取文件的创建时间

def getFileCreateTime(filePath):
    t = os.path.getctime(filePath)
    return t

10.在某一路径下查找文件名符合特定字符串的文件

def findFileByStr(findPath,findFile):
    flag = 0
    fileList = traverseDir(findPath,False)
    for file in fileList:
        fileName = os.path.basename(file)
        if findFile == fileName:
            flag = 1
            return file
    if flag == 0:
        return False
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值