Python練習題 10-1 Python 學習筆記

10-1 Python 學習筆記:在文本編輯器中新建一個文件,寫幾句話來總結一下你至
此學到的 Python 知識,其中每一行都以“In Python you can”打頭。將這個文件命名爲
learning_python.txt,並將其存儲到爲完成本章練習而編寫的程序所在的目錄中。編寫一
個程序,它讀取這個文件,並將你所寫的內容打印三次:第一次打印時讀取整個文件;
第二次打印時遍歷文件對象;第三次打印時將各行存儲在一個列表中,再在 with 代碼
塊外打印它們。

#coding:utf-8
filename='learning_python.txt'
with open(filename) as file_object:
    #第一次打印讀取整個文件
    read=file_object.read()
    print(read)
    #第二次打印遍歷文件對象
with open(filename) as file_object:
    for line in file_object:        
        print(line)
with open(filename) as file_object:
    #第三次打印將各行存儲在一個列表中
    lines=file_object.readlines()

for line in lines:
    print(line.rstrip())    

之前我就open一次,然後運行三種方法,結果只打開了一次。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章