Python 輸入和輸出

weixin_33816946發表於2017-11-02
  • Python 輸入:

   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() 如果返回一個空字串, 說明已經已經讀取到最後一行。

f.readlines()

 返回該檔案中包含的所有行。
如果設定可選引數 sizehint, 則讀取指定長度的位元組, 並且將這些位元組按行分割。

f.write()

 f.write(string) 將 string 寫入到檔案中, 然後返回寫入的字元數。

f.tell()

 返回檔案物件當前所處的位置, 它是從檔案開頭開始算起的位元組數。

f.seek()

如果要改變檔案當前的位置, 可以使用 f.seek(offset, from_what) 函式。

f.close()

 在文字檔案中 (那些開啟檔案的模式下沒有 b 的), 只會相對於檔案起始位置進行定位。

當你處理完一個檔案後, 呼叫 f.close() 來關閉檔案並釋放系統的資源,如果嘗試再呼叫該檔案,則會丟擲異常。

 

 

  • Python 輸出:

  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'))"

 

相關文章