iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 24
0
自我挑戰組

Python 學習筆記系列 第 24

Day24 Python 基礎 - 文件操作_V2

  • 分享至 

  • twitterImage
  •  

接下來實做一下怎麼對二進制文件做操作

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

f = open('foo.txt', 'rb', encoding='utf-8')     # 讀取二進制文件
print(f.readline())
print(f.readline())
print(f.readline())
f.close()

---------------執行結果---------------

Traceback (most recent call last):
  File "/Python/project/path/file_operation.py", line 4, in <module>
    f = open('foo.txt', 'rb', encoding='utf-8')     # 讀取二進制文件
ValueError: binary mode doesn't take an encoding argument

Process finished with exit code 1

若是讀取二進制文件,就不需要傳encoding編碼的參數給它,否則就會報錯,試試把encoding拿掉看看會有什麼結果?

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

f = open('foo.txt', 'rb')     # 讀取二進制文件
print(f.readline())
print(f.readline())
print(f.readline())
f.close()

---------------執行結果---------------

b'----------\xe6\x88\x91\xe6\x98\xaf\xe7\xac\xac\xe4\xb8\x80\xe8\xa1\x8c----------\n'
b'----------\xe6\x88\x91\xe6\x98\xaf\xe7\xac\xac\xe4\xba\x8c\xe8\xa1\x8c----------\n'
b'----------\xe6\x88\x91\xe6\x98\xaf\xe7\xac\xac\xe4\xb8\x89\xe8\xa1\x8c----------\n'

Process finished with exit code 0

有看到前面多了一個b代表這個是一個`bytes-like 這個就是指二進制的文件

  1. 網路傳送,只能用二進制進行傳送
  2. 讀取二進制的文件

那既然有rb,也就有wb,那就來看一下怎麼用?

f = open('foo.txt', 'wb')     # 寫入二進制文件
f.write("Hello Binary\n")
f.close()

---------------執行結果---------------

Traceback (most recent call last):
  File "/Python/project/path/file_operation.py", line 4, in <module>
    f = open('fooo.txt', 'rb')     # 讀取二進制文件
TypeError: a bytes-like object is required, not 'str'

Process finished with exit code 1

出現TypeError: a bytes-like object is required, not 'str' 這是說明不能是一個字符串,所以我們要把字符串轉成bytes類型(可以回頭參考一下)

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

f = open('foo.txt', 'wb')     # 寫入二進制文件
f.write("Hello Binary\n".encode())
f.close()

---------------執行結果---------------
觀察文件內容:

Hello Binary

咦!奇怪,為什麼看到的還是一個字符串?其實存的時候不是以0101儲存的,而是文件以二進制編碼儲存

知識點:

U 表示在讀取時,會將\r\n\r\n自動轉換成\n (與 r 或 r+ 模式使用)

  • rU
  • r+U

b 表示處理二進制文件 (如:FTP上傳ISO檔的文件,Linux可以怱略,但windows處理二進制文件時,需要標注)


上一篇
Day23 Python 基礎 - 文件操作_V2
下一篇
Day25 Python 基礎 - 文件操作_V2
系列文
Python 學習筆記29
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言