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 datetime

with 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

这里写图片描述
发现包名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 datetime

with 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 datetime

with 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'

将上述路径改为

r'C:\Users\hhh\Desktop\sample.txt'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值