1. 程式人生 > >Windows下python3生成UTF8的CSV文件和sha256sum踩坑記錄

Windows下python3生成UTF8的CSV文件和sha256sum踩坑記錄

二進制文件 ref enc lin python腳本 題解 light not 打開文件

CSV的坑

在Ubuntu下是簡單的寫入完事

import csv
...
    with open(filename, ‘w‘) as output:
        f = csv.writer(output)
        f.writerow(results[0].keys())

.在win7下, 用msys2環境執行同一個python腳本, 發現生成的csv有兩個問題: 1)有空行, 2)編碼變成了GB2312

關於空行的問題, 百度的結果都是open(filename, ‘wb‘)來解決, 但是在python3下會報

TypeError: a bytes-like object is required, not ‘str‘

.最終在stackoverflow上找到答案是python3的csv處理改了, 用binary時不能用str, https://stackoverflow.com/questions/35100280/python3-csv-writerows-typeerror-str-does-not-support-the-buffer-interface

解決辦法是用 newline=‘‘

with open(filename, "w", newline="")

.空行問題解決了, 然後是編碼問題

百度上那種在寫入時實時轉換編碼的方案肯定是有問題的, 最終找到的解決辦法是使用unicodecsv替換csv, 然後writer裏帶上參數 encoding=‘utf-8‘

import unicodecsv as csv
...
    f = csv.writer(output, encoding=‘utf-8‘)

.但是又報了TypeError錯誤

TypeError: a bytes-like object is required, not ‘str‘

咦這不是剛解決過嗎, 看了下unicodecsv的使用說明 https://pypi.org/project/unicodecsv/0.14.1/ 這貨要用binary模式打開文件, 所以要改為

with open(filename, ‘wb‘) as output:

.於是那個newline=‘‘的參數也不需要了.

sha256sum的坑

在win7下, sha256sum的結果會在文件名前面默認加星號, 而在ubuntu下, 默認不加星號, 關於星號的解釋是這樣的

The sums are computed as described in FIPS-180-2.  When checking, the input
should be a former output of this program.  The default mode is to print a
line with checksum, a space, a character indicating input mode (‘*‘ for binary,
‘ ‘ for text or where binary is insignificant), and name for each FILE.

看起來可以用-t參數強制指定使用text格式, 這樣前面就不會出現星號了, 但是對結果會不會有影響呢? 測試了一個windows下創建的文本文件

Milton@ MSYS /d/
$ sha256sum -t win_text.txt
77a6b0ba40dd08f35c056386a248c0aab2de7fec0b1a2865cd41d09842147db5  win_text.txt

Milton@ MSYS /d/
$ sha256sum -b win_text.txt
77a6b0ba40dd08f35c056386a248c0aab2de7fec0b1a2865cd41d09842147db5 *win_text.txt

.以及一個二進制文件

Milton@ MSYS /d
$ sha256sum -t 2018-12-31_2.zip
86dd42cae6b42420b60b8d35bd6168732e974c44a812486fdbbe5131b23dce79  2018-12-31_2.zip

Milton@ MSYS /d
$ sha256sum -b 2018-12-31_2.zip
86dd42cae6b42420b60b8d35bd6168732e974c44a812486fdbbe5131b23dce79 *2018-12-31_2.zip

.看來也沒有影響, 所以就在windows下增加-t參數避免輸出星號吧

Windows下python3生成UTF8的CSV文件和sha256sum踩坑記錄