Python随笔
1
当Python出现路径错误时候,某一个模块不在Python默认的安装目录,导包的时候出现错误
例如:
>import demo3
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import demo3
ImportError: No module named demo3
当出现这种错误的时候,解决方法:将模块的路径添加到Python的执行环境下
In[3]: import sys
In[4]: sys.path.extend(['C:\\Users\\zmj\\Desktop'])
2
Python文件中的内容修改后,比如新写了一个函数def new():保存后在IDE中用到new()后会出现报错:
解决方法:reload(demo3)
注意demo3是一个模块,demo.py
3
Python del的用法
In[60]: var = 2
In[61]: print var
2
In[62]: del var
In[63]: print var
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-63-e722e4cbd224>", line 1, in <module>
print var
NameError: name 'var' is not defined
4
Python中is 和==的区别:
Python中的对象包含三要素:id、type、value
其中id用来唯一标识一个对象,type标识对象的类型,value是对象的值
is判断的是a对象是否就是b对象,是通过id来判断的
==判断的是a对象的值是否和b对象的值相等,是通过value来判断的
如下代码或许可以帮助你理解。
In[86]: a = 1
In[87]: b = 1.0
In[88]: a is b
Out[88]: False
In[89]: a ==b
Out[89]: True
In[90]: id(a)
Out[90]: 1307776
In[91]: id(b)
Out[91]: 61213352
In[92]: a = 1
In[93]: b = 1
In[94]: a is b
Out[94]: True
In[95]: a == b
Out[95]: True
In[96]: id(a)
Out[96]: 1307776
In[97]: id(b)
Out[97]: 1307776
5
def printinfo(arg1,*vartuple):
print '输出:'
print arg1
for var in vartuple:
print var
return
In[34]: demo3.printinfo(80)
输出:
80
In[35]: demo3.printinfo(80,20,100,29)
输出:
80
20
6
In[36]: sum = lambda arg1,arg2: arg1+arg2
In[37]: print '相加后的值为',sum(10,20)
相加后的值为 30
In[38]: print '相加后的值为:',sum(20,20)
相加后的值为: 40
7
In[46]: fo = open('foo.txt','wb')
In[47]: print '文件名',fo.name
文件名 foo.txt
In[48]: print '是否已经关闭',fo.closed
是否已经关闭 False
In[49]: print '访问模式',fo.mode
访问模式 wb
In[50]: print '末尾是否强制加空格',fo.softspace
末尾是否强制加空格 0
In[51]: fo.close()
In[52]: print fo.closed
True
# 打开一个文件
fo = open("foo.txt", "wb")
fo.write( "www.runoob.com!\nVery good site!\n");
# 关闭打开的文件
fo.close()
# 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10);
print "读取的字符串是 : ", str
# 关闭打开的文件
fo.close()
# 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10);
print "读取的字符串是 : ", str
# 查找当前位置
position = fo.tell();
print "当前文件位置 : ", position
# 把指针再次重新定位到文件开头
position = fo.seek(0, 0);
str = fo.read(10);
print "重新读取字符串 : ", str
# 关闭打开的文件
fo.close()