我使用的Python版本為3.5.2
,嘗試用zipfile
模塊的zipfile.ZipFile.open
方法打開一個(gè)壓縮包中的文本文件時(shí),即使使用了文檔中要求的rU
參數(shù),打開時(shí)仍然是以二進(jìn)制數(shù)據(jù)格式打開的,百思不得其解。
代碼:
>>> import zipfile
>>> zf = zipfile.ZipFile('/Users/chiqingjun/Downloads/top-1m.csv.zip')
>>> zf.namelist()
['top-1m.csv']
>>> f = zf.open(zf.namelist()[0], mode='rU')
>>> f
<zipfile.ZipExtFile name='top-1m.csv' mode='rU' compress_type=deflate>
>>> f.readline()
b'1,google.com\n'
# 仍然是二進(jìn)制數(shù)據(jù)
官方文檔(3.5.2版本):
其實(shí)最后輸出的二進(jìn)制, 和zipfile
無(wú)關(guān), 是和py3.5
有關(guān), 你可以在輸出的結(jié)果解碼, 就能得到字符類型了
content = f.readline()
print(content.decode('utf8'))
文檔已經(jīng)說了呀,rU
是 通用換行符
,并且將在3.6 移除此模式。
壓縮文件以二進(jìn)制讀取字節(jié)內(nèi)容是應(yīng)該的,后面如何轉(zhuǎn)碼由程序員決定。
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)