open 函數(shù)可以打開一個(gè)文件。超級(jí)簡(jiǎn)單吧?大多數(shù)時(shí)候,我們看到它這樣被使用:
f = open('photo.jpg', 'r+')
jpgdata = f.read()
f.close()
有三個(gè)錯(cuò)誤存在于上面的代碼中。你能把它們?nèi)赋鰜韱幔?/p>
正確的用法:
with open('photo.jpg', 'r+') as f:
jpgdata = f.read()
open的第一個(gè)參數(shù)是文件名。第二個(gè)(mode 打開模式)決定了這個(gè)文件如何被打開。
- 讀取文件,傳入r
- 讀取并寫入文件,傳入r+
- 覆蓋寫入文件,傳入w
- 在文件末尾附加內(nèi)容,傳入a
以二進(jìn)制模式來打開,在mode字符串后加一個(gè)b
例子:讀取一個(gè)文件,檢測(cè)它是否是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))