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的成本低