讀取檔案時,常常需要檢查其中的每一行,可能需要查詢特定的資訊,或者以某種方式修改檔案中的檔案。with open('text.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
使用關鍵字with時,open()返回的檔案物件只在with**塊內可用。如果要在with**塊外訪問檔案的內容,可在with**塊內將檔案的各行儲存在乙個列表中,並在with**塊外使用該列表。filename = 'text.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
filename = 'text.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write('i love programming.')
異常:管理程式執行期間發生的錯誤。如果編寫了處理該異常的**,程式將繼續執行,如果未對異常進行處理,程式將停止並報告錯誤。
使用try-except-else**塊來處理可能引發的異常
try:
print(5/0)
except zerodivisionerror:
print('you can't divide by zero.')
while true:
first_number = input('first_numabe:')
if first_number == 'q':
break
second_number = input('second_number:')
if second_number == 'q'
break
try:
result = int(first_number) / int(second_number)
except:
print('you can't divide by 0 !')
else:
print(result)
python學習筆記(三)
python的序列 列表,元組,字串都是列表,列表的主要特點是索引和切片操作 序列的基本操作 1.len 求序列的長度 2.連線兩個序列 3.重複序列元素 4.in判斷序列是否在元組中 5.max 返回最大值 6.min 返回最小值 7.cmp tup1,tup2 比較兩個序列的值 元組 元組和字串...
python學習筆記三
一 輸出 print的幾種用法 print hello world hello world中間有空格 print hello wolrd helloworld 中間沒有空格 print hello wolrd helloworld 中間沒有空格 print hello world hello wor...
python學習筆記(三)
list也可以直接做加法 a 1,2 a 3 a 1,2,3 lambda用來定義匿名函式 lambda x x 2.0 lambda x x 2.0 平方是用 student torture不理解 for可以各種巢狀 ppl alice bob carol doug excited ppl e f...