python部分基础三
1、在学习python时,最简单的就是输出 hello
正文如下(py2.7):
#!usr/bin/python
print ‘hello’
为什么第一行是#!usr/bin/python ,其作用是,告诉操作系统在执行这个脚本时,调用/usr /bin下的python解析器
还有人会写成 #!usr/bin/env python 这是因为,不是所有人都会把python安装在默认的/usr/bin/下 ,所以加上env 则在开始系统会现在env设置里找到python的安装路径,在调用对应路径下的python
文件异常处理
1、>>> import os//导入os模块
>>> os.getcwd()//当前工作目录是什么
'D:\\Python27'
>>> os.chdir('../headfistpython/chapter3')
>>> os.getcwd()
'D:\\headfistpython\\chapter3'
2、读取文件:
>>> data = open('sketch.txt')
>>> print data.readline()//读取一行
hello
>>> print data.read()//读取整个文件
haha
ahaha
>>> data.close()//关闭文档
文件处理-》打开文件-》读取文件内容-》处理后关闭文件
3、split(sep,[maxsplit])
4、find 通过find的返回值 判断
5、异常处理
对于会出现异常的情况,放入try/cath模块中-
其次增加更多的异常代码的处理
下面是对 一个解析的文件是否存在进行处理
>>> import os
>>> if os.path.exists('du.txt')://判断文件是否存在,如果存在则继续执行,不存在则提示文件丢失
data = open('du.txt')
for each in data:
if not each.find(':') == -1:
(role,num)= each.split(':',1)
print role
print num
print(role,num)
data.close()
else:
print ('The data file is missing')
man
is this the tight room foe an atgumen?
('man', ' is this the tight room foe an atgumen?\n')
other man
I've told you once.
('other man', " I've told you once.\n")
man
No you haven't!
('man', " No you haven't!\n")
other man
Yes I have.
('other man ', 'Yes I have.\n')
man
When?
('man', ' When?\n')
other man
now let's get one thing quites clear:i most definitely told you!
('other man', " now let's get one thing quites clear:i most definitely told you!\n")
man
no you didn't!
('man', " no you didn't!")
//修改打开文件名称
则提示
The data file is missing
使用try/catch
>>> try:
data = open('du.txt')
for each in data :
try:
(role,num)= each.split(':',1)
print role
print '++++++++++++++++++++++++++'
print num
print '++++++++++++++++++++++++'
print (role,num)
except:
pass
except:
print 'the is not exists'
the is not exists
>>>
//无论使用if else 还是try catch 均能达到处理异常的目的,但是使用try的成本低