標籤:hint read repr site 開啟檔案 set hat 讀取 包含
1. 讀和寫檔案
# 開啟一個檔案f = open("/tmp/foo.txt", "w") #第一個參數是要開啟的檔案名稱,第二個參數 w是寫入,r 是唯讀f.write( "Python 是一個非常好的語言。\n是的,的確非常好!!\n" )# 關閉開啟的檔案f.close()
2. 檔案對象的方法:
| f.read() |
為了讀取一個檔案的內容,調用 f.read(size), 這將讀取一定數目的資料, 然後作為字串或位元組對象返回。 |
| f.readline() |
f.readline() 會從檔案中讀取單獨的一行。分行符號為 ‘\n‘。f.readline() 如果返回一個Null 字元串, 說明已經已經讀取到最後一行。 |
| f.readlines() |
返回該檔案中包含的所有行。 如果設定選擇性參數 sizehint, 則讀取指定長度的位元組, 並且將這些位元組按行分割。 |
| f.write() |
f.write(string) 將 string 寫入到檔案中, 然後返回寫入的字元數。 |
| f.tell() |
返迴文件對象當前所處的位置, 它是從檔案開頭開始算起的位元組數。 |
| f.seek() |
如果要改變檔案當前的位置, 可以使用 f.seek(offset, from_what) 函數。 |
| f.close() |
在文字檔中 (那些開啟檔案的模式下沒有 b 的), 只會相對於檔案起始位置進行定位。 當你處理完一個檔案後, 調用 f.close() 來關閉檔案並釋放系統的資源,如果嘗試再調用該檔案,則會拋出異常。 |
1. 運算式語句
2. print () 函數
3. 使用檔案對象的 write() 方法,標準輸出檔案可以用 sys.stdout 引用。
可以使用 str.format() 函數來格式化輸出值。
#括弧及其裡面的字元 (稱作格式化欄位) 將會被 format() 中的參數替換。>>> print(‘{}網址: "{}!"‘.format(‘百度‘, ‘www.baidu.com‘))百度網址: "www.baidu.com!"#在括弧中的數字用於指向傳入對象在 format() 中的位置,>>> print(‘{0} 和 {1}‘.format(‘Google‘, ‘Zero‘))Google 和 Zero>>> print(‘{1} 和 {0}‘.format(‘Google‘, ‘Zero‘))Zero 和 Google#如果在 format() 中使用了關鍵字參數, 那麼它們的值會指向使用該名字的參數。>>> print(‘{name}網址: {site}‘.format(name=‘百度‘, site=‘www.baidu.com‘))菜鳥教程網址: www.baidu.com#位置及關鍵字參數可以任意的結合:>>> print(‘網站列表 {0}, {1}, 和 {other}。‘.format(‘Google‘, ‘Baidu‘, other=‘Taobao‘))網站列表 Google, Baidu, 和 Taobao。
可以使用 repr() 或 str() 函數來實現將輸出的值轉成字串。
- str(): 函數返回一個使用者易讀的表達形式。
- repr(): 產生一個解譯器易讀的表達形式。
>>> s = ‘Hello, Zero‘>>> str(s)‘Hello, Zero‘>>> repr(s)"‘Hello, Zero‘">>> str(1/7)‘0.14285714285714285‘>>> x = 10 * 3.25>>> y = 200 * 200>>> s = ‘x 的值為: ‘ + repr(x) + ‘, y 的值為:‘ + repr(y) + ‘...‘>>> print(s)x 的值為: 32.5, y 的值為:40000...>>> # repr() 函數可以逸出字元串中的特殊字元... hello = ‘hello, Zero\n‘>>> hellos = repr(hello)>>> print(hellos)‘hello, Zero\n‘>>> # repr() 的參數可以是 Python 的任何對象... repr((x, y, (‘Shen‘, ‘Zero‘)))"(32.5, 40000, (‘Shen‘, ‘Zero‘))"
Python 輸入和輸出