Python IO編程

來源:互聯網
上載者:User

標籤:圖片   傳輸   value   size   rip   while   操作檔案   部分   通過   

9 IO編程

在Python中,檔案讀寫是通過open()函數開啟的檔案對象完成的。使用with語句操作檔案IO是個好習慣。

讀檔案

         try:

    f = open(‘/path/to/file‘, ‘r‘)

    print(f.read())

finally:

    if f:

        f.close()

 python引入了with語句來自動幫我們調用close()方法:

        with open(‘/path/to/file‘, ‘r‘) as f:

    print(f.read())

 要讀取二進位檔案,比片、視頻等等,用‘rb‘模式開啟檔案即可

 >>> f = open(‘/Users/michael/test.jpg‘, ‘rb‘)

>>> f.read()

b‘\xff\xd8\xff\xe1\x00\x18Exif\x00\x00...‘ # 十六進位表示的位元組

編碼不規範 ,忽視錯誤的寫法

 f = open(‘/Users/michael/gbk.txt‘, ‘r‘, encoding=‘gbk‘, errors=‘ignore‘)

 f.readline(),f.read(size)固定讀取檔案大小

 

 寫檔案

 ----------

 9.2字元位元組  StringIo  BytesIo

 StringIO和BytesIO是在記憶體中操作str和bytes的方法,使得和讀寫檔案具有一致的介面。

 from io import StringIO

>>> f = StringIO(‘Hello!\nHi!\nGoodbye!‘)

>>> while True:

...     s = f.readline()

...     if s == ‘‘:

...         break

...     print(s.strip())

 ----------StringIO顧名思義就是在記憶體中讀寫str。

 >>> from io import BytesIO

>>> f = BytesIO()

>>> f.write(‘中文‘.encode(‘utf-8‘))

6

>>> print(f.getvalue())

b‘\xe4\xb8\xad\xe6\x96\x87‘

###BytesIO實現了在記憶體中讀寫bytes,

-------------

9.3操作檔案和目錄

 os.environ.get(‘PATH‘)

 os.path.split()函數,這樣可以把一個路徑拆分為兩部分,後一部分總是最後層級的目錄或檔案名稱:

 >>> os.path.split(‘/Users/michael/testdir/file.txt‘)

(‘/Users/michael/testdir‘, ‘file.txt‘)

 

要列出所有的.py檔案

>>> [x for x in os.listdir(‘.‘) if os.path.isfile(x) and os.path.splitext(x)[1]==‘.py‘]

 

-----------

9.4 Python提供了pickle模組來實現序列化。我們把變數從記憶體中變成可儲存或傳輸的過程稱之為序列化

>>> import pickle

>>> d = dict(name=‘Bob‘, age=20, score=88)

>>> pickle.dumps(d)

b‘\x80\x03}q\x00(X\x03\x00\x00\x00ageq\x01K\x14X\x05\x00\x00\x00scoreq\x02KXX\x04\x00\x00\x00nameq\x03X\x03\x00\x00\x00Bobq\x04u.‘

 

pickle.dump()直接把對象序列化後寫入一個file-like Object:

>>> f = open(‘dump.txt‘, ‘wb‘)

>>> pickle.dump(d, f)

>>> f.close()

 

當我們要把對象從磁碟讀到記憶體時,可以先把內容讀到一個bytes,然後用pickle.loads()方法還原序列化出對象

>>> f = open(‘dump.txt‘, ‘rb‘)

>>> d = pickle.load(f)

>>> f.close()

>>> d

{‘age‘: 20, ‘score‘: 88, ‘name‘: ‘Bob‘}

 

json

 

Python IO編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.