Python 輸入和輸出

來源:互聯網
上載者:User

標籤:hint   read   repr   site   開啟檔案   set   hat   讀取   包含   

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

 

Python 輸入和輸出

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.