python常用函数和方法

1,执行脚本的时候传递参数,argparse

import argparse

ap=argparse.ArgumentParser()
#实例化一个argparse对象
ap.add_argument('url', type=str, help='url of the alarm')
#这个是必选参数
ap.add_argument('--almtype','-k', type=str,default='0', help='what kind of alarm',required=False)
#可选参数,不写的话默认为0
args = ap.parse_args()
#获取脚本传递进来的参数

url=args.url
almtype=args.almtype
#把用户传递进来的参数变成了变量

 2,分离文件路径和名称,名字和类型后缀

import os
 
filepath = "D:/test/test.jpg"
(filepath, tempfilename) = os.path.split(filepath)
#分离路径和名称
(filename, extension) = os.path.splitext(tempfilename)
#分离名称和后缀

3,拷贝文件

import os
import shutil

source = 'current/test/test.jpg'
target = '/prod/new'

shutil.copy(source, target)

 4,判断文件还是文件夹

import os
if os.path.isdir(path):
    print "dir"
elif os.path.isfile(path):
    print "file"
else:
    print "not file or dir"

5,想要n位整数,不够就补0

a="%06d"%10

注意a此时是字符串

6,重命名文件或者文件夹

import os
#rename dir
srcDir = './testDir/beforeDir'
dstDir = './testDir/afterDir'
try:
    os.rename(srcDir,dstDir)
except Exception as e:
    print 'rename dir fail\n'
else:
    print 'rename dir success\n'

#rename file
srcFile
= './testDir/12333.txt' dstFile = './testDir/45666.txt' try: os.rename(srcFile,dstFile) except Exception as e: print 'rename file fail\n' else: print 'rename file success\n'

 7,格式化时间

import time
ctime=time.localtime()
timestr=time.strftime("%Y-%m-%d %H:%M:%S", ctime)

 8,使用pymysql链接数据库

插入数据:

import pymysql
import os

##把某文件夹下的图片名称添加到数据库

"""数据库结构:DROP TABLE IF EXISTS `t_check_img`;
CREATE TABLE `t_check_img` (
  `id` int(11) NOT NULL,
  `imgname` varchar(255) NOT NULL,
  `imgtype` varchar(255) NOT NULL,
  `python` int(11) DEFAULT NULL,
  `cnopart` int(11) DEFAULT NULL,
  `cpart` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
"""
db = pymysql.connect('localhost','root','xxx','daqingdb')
#参数分别是,localhost,用户名,密码,数据库名称
cursor=db.cursor()
#获取一个游标
origin_img_path="e:\新建文件夹\jpg0512"
imgdir=os.listdir(origin_img_path)
idx=1
imgtype="test"
for i in imgdir:
    (filename, suffix) = os.path.splitext(i)
    if suffix==".jpg":
        imgtype="jpg"
    elif suffix==".bmp":
        imgtype="bmp"
    else:
        print("img name:",i,"not up to db")
        continue
#通过后缀判断图片类型,只提交jpg和bmp
    try:
        sqldb = "insert into `t_check_img` (`id` ,`imgname`,`imgtype`) values('%d','%s','%s')"%(idx,filename,imgtype)
        hehe=cursor.execute(sqldb)
#提交数据,但是暂时还不会执行,直到db.commit的时候才会执行
    except exception as e:
        print("insert into db error",e)
        break
    print(idx)
    idx+=1
db.commit()
print("ok")

cursor.close()
db.close()

查询数据比较容易:

import pymysql

db = pymysql.connect('localhost','root','xxx','daqingdb')
cursor=db.cursor()
try:
    sqldb = "select imgname from t_check_img where imgtype='jpg'"
    hehe =cursor.execute(sqldb)
    data = cursor.fetchall()
    print(data)

except Exception as e:
    print(e)
    
cursor.close()
db.close()

 9,写出到本地文件

import os
def Write_Text(file_name,contant):
    # file_name = 'test.txt'
    with open(file_name,"a+") as f:
        f.writelines(contant)
        f.writelines("\n")

 从本地文件读取内容,修改然后替换保存该文件

import os
import json

jsonfile="./zg.txt"

with open(jsonfile,'r+') as f:
    #orign=f.readlines()
    #print(orign)
    contentlist=json.load(f)
    if contentlist['zg']['sd']:
        contentlist['zg']['sd']='250000'
    else:
        exit(0)
    jsonnew=json.dumps(contentlist)
    f.seek(0)
    f.truncate()   #clear before write
    f.write(jsonnew)
print('ok')

 10,打印出所有的父类

        import inspect
        parents = set(inspect.getmro(CustomImageItem)[1:])

        # 打印所有父类的名称,CustomImageItem是类名
        for parent in parents:
            print("---------------------",parent.__name__)

 

posted @ 2023-09-15 10:11  0点0度  阅读(23)  评论(0编辑  收藏  举报