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'
. 最终在 Stack Overflow 上找到答案是 python3 的 CSV 处理改了, 用 binary 时不能用 str,
解决办法是用 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 参数避免输出星号吧
来源: http://www.bubuko.com/infodetail-2907147.html