open 函數(shù)可以打開一個文件。超級簡單吧?大多數(shù)時候,我們看到它這樣被使用:
f = open('photo.jpg', 'r+')
jpgdata = f.read()
f.close()
有三個錯誤存在于上面的代碼中。你能把它們全指出來嗎?
正確的用法:
with open('photo.jpg', 'r+') as f:
jpgdata = f.read()
open的第一個參數(shù)是文件名。第二個(mode 打開模式)決定了這個文件如何被打開。
- 讀取文件,傳入r
- 讀取并寫入文件,傳入r+
- 覆蓋寫入文件,傳入w
- 在文件末尾附加內容,傳入a
以二進制模式來打開,在mode字符串后加一個b
例子:讀取一個文件,檢測它是否是JPG
import io
with open('photo.jpg', 'rb') as inf:
jpgdata = inf.read()
if jpgdata.startswith(b'\xff\xd8'):
text = u'This is a JPEG file (%d bytes long)\n'
else:
text = u'This is a random file (%d bytes long)\n'
with io.open('summary.txt', 'w', encoding='utf-8') as outf:
outf.write(text % len(jpgdata))