我最近迁移到了Py 3.5.这段代码在Python 2.7中正常工作:
with open(fname, 'rb') as f:
    lines = [x.strip() for x in f.readlines()]
for line in lines:
    tmp = line.strip().lower()
    if 'some-pattern' in tmp: continue
    # ... code
升级到3.5后,我得到了:
TypeError: a bytes-like object is required, not 'str'
最后一行的错误(模式搜索代码).
我已尝试.decode()在语句的任何一侧使用该函数,也尝试过:
if tmp.find('some-pattern') != -1: continue
- 无济于事.
我能够迅速解决几乎所有2:3的问题,但这个小小的陈述让我烦恼.
在运行Windows XP专业版的Python 2.7中:
import csv
outfile = file('test.csv', 'w')
writer = csv.writer(outfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['hi','dude'])
writer.writerow(['hi2','dude2'])
outfile.close()
它生成一个文件test.csv,每行有一个额外的\ r \n,如下所示:
hi,dude\r\r\nhi2,dude2\r\r\n
而不是预期的:
hi,dude\r\nhi2,dude2\r\n
为什么会发生这种情况,或者这实际上是期望的行为?
我的python脚本生成json文件.我必须支持这个在Windows和Linux上运行的python文件.问题是Windows和Linux上的回车差异.当我在Windows上运行此代码时,它输出CRLF json.当我在linux上运行它时输出LF json.
那么如何在python3.5中进行json转储时显式设置回车?我想
import json
fpath = "hoge.json"
data = {"AGE": 12, "HOGE": [{"GUA": 3}]}
with open(fpath, 'wt', encoding="utf-8") as outfile:
    json.dump(data, outfile, indent=4, sort_keys=True, ensure_ascii=False)