python學習(8)————讀取文件

我們已經知道了如何使用argv參數獲取數據以及使用輸入獲取數據,現在我們開始學習從文件中獲取數據。
這次讀文件,需要我們編寫兩個文件,一個是執行腳本文件(ex8_1.py)一個是讀取的文檔文件(data.out),文檔文件(data.out)的內容爲:

This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

然後,我們要通過open函數打開文檔並且讀取其中數據然後再在屏幕上輸出數據,以下是讀取文件的代碼:


from sys import argv

script, filename = argv

txt = open(filename)

print "Here's your file %r:" % filename
print txt.read()

print "Type the filename again:"
file_again = raw_input("> ")

txt_again = open(file_again)

print txt_again.read()

得到的結果:
這裏寫圖片描述
這裏你可以看到,我們讀入一個文件,讀了兩次,並且沒有發現問題,這在有些語言裏面是不允許的。這是python一條非常重要的性質

發佈了21 篇原創文章 · 獲贊 10 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章