0
我有這個文件寫入功能:文件寫入和文件以UTF-16閱讀蟒蛇
def filewrite(folderpath, filename, strdata, encmode):
try:
path = os.path.join(folderpath, filename)
if not path:
return
create_dir_path(folderpath)
#path = os.path.join(folderpath, filepath)
with codecs.open(path, mode='w', encoding=encmode) as fp:
fp.write(unicode(strdata))
except Exception, e:
raise Exception(e)
其正在使用將數據寫入一個文件:
filewrite(folderpath, filename, strdata, 'utf-16')
但是,當如果嘗試閱讀該文件我得到異常:
Exception: UTF-16 stream does not start with BOM
我的文件讀取功能,如下所示:
def read_in_chunks(file_object, chunk_size=4096):
try:
while True:
data = file_object.read(chunk_size)
if not data:
break
yield data
except Exception, ex:
raise ex
def fileread(folderPath, fileName, encmode):
try:
path = os.path.join(folderPath, fileName)
fileData = ''
if os.access(path, os.R_OK):
with codecs.open(path, mode='r', encoding=encmode) as fp:
for block in read_in_chunks(fp):
fileData = fileData + block
return fileData
return ''
except Exception, ex:
raise ex
請讓我知道這裏做錯了什麼。
謝謝
在x64機器上(Windows 8.1)。試圖刪除'read_in_chunks'以及。由於某種原因無法使其工作。 – Harsh
它是'codecs.open(path,mode ='r',encoding = encmode)爲fp:'引發異常?確保用'raise'替換'raise ex',否則它會掩蓋異常開始的真實位置。 –