-
__name__ == "__main__
作用1:很多python入门的书,都会建议你把代码写成一个函数,然后在最后面统一调用,例如这样:
def main():
#具体代码
if __name__ == '__main__':
main()
作用2:如果模块是被直接运行的,则__name__ == "__main__成立运行后面的代码,如果模块被import,则下面代码不被运行。
-
try——except
如果try下面的代码出现错误,就会执行except中的代码
try:
fp = open(filename,'a',encoding='utf-8')
except:
fp = open(filename,'w',encoding='utf-8')
else: 全程没错误进去else
pass
-
with...as...
#这里wfile相当于句柄,好处就是自动回收资源,完了以后不用close
with open(filename,'a',encoding='utf-8') as wfile:
-
eval
首先eval(字符串):将字符串string对象转化为有效的表达式参与求值运算返回计算结果
(就是运行完字符串里面的内容或运算符,结果是什么类型就得到什么类型)
示例1:
def eval_test():
l='[1,2,3,4,[5,6,7,8,9]]'
d="{'a':123,'b':456,'c':789}"
t='([1,3,5],[5,6,7,8,9],[123,456,789])'
print '--------------------------转化开始--------------------------------'
print type(l), type(eval(l))
print type(d), type(eval(d))
print type(t), type(eval(t))
————————————————
<type 'str'> <type 'list'>
<type 'str'> <type 'dict'>
<type 'str'> <type 'tuple'>
示例2:
i = eval('10+2')
print(i,type(i))
结果:12 <class 'int'>
d = dict(eval(item))
#其实由于之前插入元素的时候就是按字典插入的,所以eval(item)此时已经是字典类型,加上dict应该是为了标记