1.判断关键字是否存在字典中
if "Power Supply" in demension:
print "good"
2.字典和列表的追加
alert1 = []
alert2 = {}
alert2.update(alerts) #字典的追加
alert1.append(alert2.copy()) #列表追加
3.常用的操作
1)获取当前目录用到os模块
directory = os.getcwd()
2)变量%s的用法
hostname_dir = "%s/result/" % directory
dimension_dir = "%s/result/%s/hw_check_result.txt" % (directory, hostname)
3)列举目录名称的方法
hostname_list = os.listdir(hostname_dir)
4)Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
5)判断文件是否存在os.path.exists()
if os.path.exists(dimensions_dir):
print "good"
os即operating system(操作系统),Python 的 os 模块封装了常见的文件和目录操作。
os.path模块主要用于文件的属性获取,exists是“存在”的意思,所以顾名思义,os.path.exists()就是判断括号里的文件是否存在的意思,括号内的可以是文件路径。
6)open()函数打开文件的用法
dimensions_list = open(dimension_dir)
注:open()打开后的内容是file类型
7)len()方法来查看字符串的长度
dimensions_len = len(j)
8)eval()函数,将字符串转换成字典或者列表
dimension1 = eval(dimension2)
9)如果字典是空或者列表为空
if dict =={}:
print "good"
if list ==[]:
print "good"
10)获取字典的values值
遍历大字典中
for k in dimension:
Error_Devtype = k[‘Error_Devtype‘]
获取列表中元素的值
list[0]
list[1]
4.json格式输出常用的两个方法
json.dumps()函数是将字典或者列表转化为字符串
json.loads()函数是将字符串转化为字典
5.列表中有种中文字符,并以json格式数出列表内容的解决方法
print json.dumps(alert1, encoding="UTF-8", ensure_ascii=False).encode(‘utf-8‘)
6.解决代码中中文字符乱码
#!/usr/bin/python
#-*- coding:utf-8 -*-
7.判断字典中是否有某个key
if "bmc_info" in dict:
print "good"
8.统计列表中元素的个数
counts = len(list)
9.对列表元素进行去重
news_alert3 = []
for alert4 in alert3:
if alert4 not in news_alert3:
news_alert.append(alert4)
print news_alert3
10.将列表中的元素转换成新字典中的key值
for m in range(1, counts+1):
for p in alert1:
for q in news_alert3:
if q in p.values():
news_alert3_values = []
news_alert3_values.append(m)
thisdict = dict.fromkeys(news_alert3, news_alert3_values)
print thisdict
python随笔记录
原文:https://www.cnblogs.com/stefan0616/p/12362687.html