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下创建的文本文件
[email protected] MSYS /d/ $ sha256sum -t win_text.txt 77a6b0ba40dd08f35c056386a248c0aab2de7fec0b1a2865cd41d09842147db5 win_text.txt [email protected] MSYS /d/ $ sha256sum -b win_text.txt 77a6b0ba40dd08f35c056386a248c0aab2de7fec0b1a2865cd41d09842147db5 *win_text.txt
.以及一个二进制文件
[email protected] MSYS /d $ sha256sum -t 2018-12-31_2.zip 86dd42cae6b42420b60b8d35bd6168732e974c44a812486fdbbe5131b23dce79 2018-12-31_2.zip [email protected] MSYS /d $ sha256sum -b 2018-12-31_2.zip 86dd42cae6b42420b60b8d35bd6168732e974c44a812486fdbbe5131b23dce79 *2018-12-31_2.zip
.看来也没有影响, 所以就在windows下增加-t参数避免输出星号吧
原文地址:https://www.cnblogs.com/milton/p/10213565.html