Python 错误记录(1)Fatal Python error: Py_Initialize: can't initialize sys standard streams AttributeErro

Fatal Python error: Py_Initialize: can’t initialize sys standard streams AttributeErro python3.5+pycharm ,不确定其他环境会不会报错。

from datetime import datetimewith open('C:\Users\hhh\Desktop\sample.txt', 'w') as f: f.write('今天是 ') f.write(datetime.now().strftime('%Y-%m-%d'))with open('C:\Users\hhh\Desktop\sample.txt', 'r') as f: s = f.read() print('open for read...') print(s)with open('C:\Users\hhh\Desktop\sample.txt', 'rb') as f: s = f.read() print('open as binary for read...') print(s)

**
出现如下错误 **
Fatal Python error: Py_Initialize: can’t initialize sys standard streams
AttributeError: module ‘io’ has no attribute ‘OpenWrapper’
Current thread 0x00003a68 (most recent call first):
排查过程 error1 Python 错误记录(1)Fatal Python error: Py_Initialize: can't initialize sys standard streams AttributeErro
文章图片

发现包名io有问题,在这个报名下即使是一条简单的print(’hello’)语句都会报上述错误,于是将包名改hhh(随便一个包名)。
error2 将报名改后,又出现了如下报错
**with open(‘C:\Users\hhh\Desktop\sample.txt’, ‘w’) as f:
^
SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape**
经过调试发现文件路径格式不对
C:\Users\hhh\Desktop\sample.txt

将上述路径改为
C:\\Users\hhh\Desktop\sample.txt

正确代码如下
为什么需要改成这样呢?是因为Python的字符串本身也用\转义,所以要特别注意,建议使用Python的r前缀,就不用考虑转义的问题了
from datetime import datetimewith open('C:\\Users\zhaorongrong\Desktop\sample.txt', 'w') as f: f.write('今天是 ') f.write(datetime.now().strftime('%Y-%m-%d'))with open('C:\\Users\zhaorongrong\Desktop\sample.txt', 'r') as f: s = f.read() print('open for read...') print(s)with open('C:\\Users\zhaorongrong\Desktop\sample.txt', 'rb') as f: s = f.read() print('open as binary for read...') print(s)

运行结果
open for read…
今天是 2018-04-04
open as binary for read…
b’\xbd\xf1\xcc\xec\xca\xc7 2018-04-04’
Process finished with exit code 0
使用Python的r前缀,就不用考虑转义的问题了
from datetime import datetimewith open(r'C:\Users\zhaorongrong\Desktop\sample.txt', 'w') as f: f.write('今天是 ') f.write(datetime.now().strftime('%Y-%m-%d'))with open(r'C:\Users\zhaorongrong\Desktop\sample.txt', 'r') as f: s = f.read() print('open for read...') print(s)with open(r'C:\Users\zhaorongrong\Desktop\sample.txt', 'rb') as f: s = f.read() print('open as binary for read...') print(s)

'C:\Users\hhh\Desktop\sample.txt'

【Python 错误记录(1)Fatal Python error: Py_Initialize: can't initialize sys standard streams AttributeErro】将上述路径改为
r'C:\Users\hhh\Desktop\sample.txt'

    推荐阅读