python常用库和操作的积累手册

1,glob的语法
glob类似shell的find,非常方便
用这个替代常用的os.walk(变量路径)

  for root,dirs,files in os.walk(path):
  	for file in files:
    	if file.endswith('weiming.tcl'):     #也可用正则match
 			file_path = os.path.join(root,file)
   使用 :
 import  glob
       路径列表  = glob.glob(路径+匹配file)
       glob.iglob('src/**/*.c', recursive=True)      #使用iglob进行递归搜索
    通配符语法:

https://rgb-24bit.github.io/blog/2018/glob.html

         例如:/path 路径下       abcde.log       abcde_ref.log
         匹配   abcde.log     使用   glob.glob(/path/*[!(_ref)]*.log) 
                   glob类似shell的find,非常方便
      用这个替代常用的os.walk(变量路径) 

2,copy的语法
如果a = 5, b = a,那么a和b都指向同一个数值,如果5发生变化,a和b都变化。.copy则是一层copy。如图
Python 直接赋值、浅拷贝和深度拷贝解析: https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html
字典是两层索引,因而.copy()对value就不正确了

   import copy
   b = a.copy()  # 浅复制,a和b是区分的但是二级对象如果是指向的话,指向的还是同一个
   b = copy.deepcopy(a)  # 深复制,所有子对象都不一样
   c ={"1":"a"}
   d = c.copy()    # 若通过c删除1的value值a,同步的d的也会删除a,但改变1的数值,d的key值可以不变
   d = copy.deepcopy(c)   #怎么改变c的值,d的值不受影响

3,删除字典或者删除列表的方法
参考内容:
https://blog.csdn.net/uuihoo/article/details/79496440
http://c.biancheng.net/view/2209.html
1,clear方法

dict.clear()   #   删除字典所有元素
list.clear()   #   删除列表所有元素

2, pop方法

                  list.pop[index]          # 弹出值,同时删除列表元素
                  dict.pop  (key值)        #  弹出键值对,本身的值是弹出的value, 同时字典删除元素

3 ,del方法

        del   list[index]
        del   dict [  key ]

4.,其它方法
list.remove(元素)
dict.popitem[key] # 随机删除值

4, 对比两个文件或者两段字符的异同
需要用到difflib库

   import  difflib
   text_1 = fa.read().splitlines()         #   将读取的字段进行分割
   text_2 = fb.read().splitlines()   
   text1 = [ i for i in text_1 if i not in text_2 ]     #      删除相同
   text2 = [ i for i in text_2 if i not in text_1 ]       
   diff  =  difflib.Differ()
   result = diff.compare (text1,text2)   #  result是一个带 + 和- 的行迭代器

5,关于os库的使用

  import os
  if not os.path.exists(dirs):              #判断路径是否存在
      os.makedirs(dirs)
  if not os.path.exists(filename):          #判断dir文件或者文件路径是否存在
      os.system(filename)  
  if not os.isfile(filename):             #判断是否是文件还是dir文件
  if not os.path.getsize(filename):         #判断文件是否为空
      os.remove(filename)

6,字典和json的相互转换
import json
content = json.dumps(字典, indent =4) # 将字典转化为直观格式的字符串
字典 = json.loads(字符串) #将字符串形式的格式json转化为字典
注意: 能否转json 可以先登录这个网站试一下https://www.json.cn/json/jsononline.html
7,读取shell命令的输出

 import os
process = os.popen('ls -l') # return file
output = process.read()
process.close()

8,python 并行的使用
一般同时引入time ,对比下运行时间

import time
import multiprocessing
start_time = time.asctime(time.localtime(time.time()))
print(start_time)
def abc(x)#  并行运行的函数
    return x
cores = multiprocessing.cpu_count()      #读取cpu 核数
pool = multiprocessing.Pool(processes=cores)     #  也可以自己设置processes数目

pool.map(abc,list)   # 并行化运行,abc是函数,list是列表

end_time = time.asctime(time .localtime(time.time()))
print(end_time)

注意:如果并行化处理列表处理字典, 需要用共享列表或者共享字典list = multiprocessing.Manager().list()

        list = multiprocessing.Manager().list()
import multiprocessing as mp

def f(x):
    return (x, x*x)

if __name__ == '__main__':
    pool = mp.Pool()
    inputs = range(10)
    result = dict(pool.map(f, inputs))

7,读取进程的内存数据

import psutil
timeline = []
mem_usage = []
p1 = psutil.Popen("./run", shell=True)    #执行shell脚本
while p1.poll() == None:             # 判断程序是否在运行                                      
    currt_mem_sum = 0                                                       
    child_pids = p1.children(recursive=True)     # 获取所有的子进程                       
    for child_pid in child_pids:                                                 
        if child_pid and child_pid.memory_info():                                   
            currt_mem_sum += child_pid.memory_info().rss / (1024 * 1024)       
    timeline.append(time.time() - timestart)                                        
    mem_usage.append(currt_memo_sum)                                         
    time.sleep(1)                                                                   

8,优雅的合并两个字典

  x = {'a': 1, 'b': 2}
  y = {'b': 3, 'c': 4}
  z = {**x, **y}                     # 如果key相同,则y合并x

9,批量给变量赋值

  #方法1 使用locals:
  for i in range(0,10):
  	  locals()["temp" + str(i)] = i
  #方法2 使用exec函数:
  for i in range(0,10):
  	  exec("temp" + str(i) + "= i")
  #使用方法1,不能给实例变量赋值,使用方法2则可以

10,re.sub灵活的替换

import re
src = 'everything is alright.'
re.sub('(every).*?(\\s.*\\.)',r'\1body\2',src) # everybody is alright.

11,判断文件是否为空

os.path.getsize(filename)
os.path.exists(filename)

12,configparser模块的使用(最详细版)

https://www.cnblogs.com/zhangxianrong/p/14690380.html

config = configparser.ConfigParser()
config.read(configfile)
groups = config.sections()   # 返回列表
dicta = config._section      # 返回order dict (需要再转化字典)
b = config._section[group][a]       #  类似当字典用
b = read_options(group, a)

13,带颜色的log输出

import logging
class Log():
    logging.basicConfig(format='%(asctime)s [%(levelname)s]-> line:%(lineno)d : %(message)s', level=logging.INFO)
    @classmethod
    def info(cls, msg):
        return logging.info(("\033[1;42m {} \033[0m").format(msg))
    @classmethod
    def warning(cls, msg):
        return logging.warning(("\033[1;43m {} \033[0m").format(msg))
    @classmethod
    def error(cls, msg):
        return logging.error(("\033[1;41m {} \033[0m").format(msg))

14, 对list的list去重
dic = list(set([tuple(t) for t in dic]))
dic = [list(v) for v in dic]

15,python 树形数据的操作
关于element的文档
python关于elementtree的文档
关于xmldom的文档
知乎相关element的文档
16,format 函数转进制

format(10, 'b')
'1010'
format(10, 'o')
format(10, 'x')  #大写转大写字母 X-> F,   x->f

17,re.sub命名分组易出错,无法分辨\1和\10

re.sub(r'(\d+\.\d+\.\d+\.)(\d$)',lambda m: m.group(1)+'0'+m.group(2),'192.168.1.8')
'192.168.1.08'

18,list去重不改变原来顺序

l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
l2.sort(key=l1.index) 
#或者
l1 = ['b','c','d','b','c','a','a']
l2 = sorted(set(l1),key=l1.index)

19,lambda的用法
1,lambda 相当于函数
lambda x: 2x 带上括号整体相当于一个函数的名称
例如:(lambda x: 2x)(2)
2, 和sort一起用
dica = dict(sorted(org_dic.items(), key=lambda x: x[0]))

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值