python3 一些编码问题

str和bytes相互转换

str -> bytes encode bytes -> str decode 有可能失败

例子1(文本读)


f1 = open('/etc/passwd','r')
f2 = open('/etc/passwd','rb')

print(f1.readline())
print(f2.readline())


输出

总结: 使用内部读的对象是不同的!

例子2(文本写)


f = open('/tmp/hello1','w')
print(f)
f.write('hello')

f = open('/tmp/hello2','wb')
print(f)
f.write(b'hello')
# f.write('hello'.encode('utf-8'))


输出

总结写是不一样的,以哪种类型打开,写的对象要符合,以TextIOWrapper打开,写就要str类型写, 同理, 以BufferedWriter打开,写就要bytes

例子3


import subprocess

p = subprocess.Popen(['cat'],stdin=subprocess.PIPE)
print(p.stdin)
p = subprocess.Popen(['cat'],stdin=subprocess.PIPE,bufsize=1, universal_newlines=True)
print(p.stdin)


输出:

<_io.BufferedWriter name="4"> <_io.TextIOWrapper name="5" encoding="UTF-8"> 总结: 当以行模式打开时是是使用 TextIOWrapper包装
Loading Disqus comments...
Table of Contents