learn python 3 the hard way 第17练习 exercise17 错误提示:UnicodeDecodeError: 'gbk' codec can't decode...

在执行《Learn Python the Hard Way》的练习时遇到'gbk'编码错误。错误源于powershell创建的UTF-16编码文件与Python默认的UTF-8解码不匹配。通过修改powershell创建文件的编码为UTF-8或在Python脚本中使用二进制模式读取并解码文件,可以避免该错误。这两种方法都无需改动原有脚本的结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

运行 “Learn Python the Hard Way” 里的代码时出现的报错。代码:

  1. from sys import argv
  2. from os.path import exists
  3. script, from_file, to_file = argv
  4. print(f"Copying from {from_file} to {to_file}")
  5. we could do these two on one line, how?

  6. in_file = open(from_file)
  7. indata = in_file.read()
  8. print(f"The input file is {len(indata)} bytes long")
  9. print(f"Does the output file exsit? {exists(to_file)}")
  10. print(“Ready, hit RETURN to continue, CTRL-C to abort.”)
  11. input()
  12. out_file = open(to_file, ‘w’)
  13. out_file.write(indata)
  14. print(“Alright, all done.”)
  15. out_file.close()
  16. in_file.close()
    照抄书本在 Terminal 上输入的命令:
    $ echo “This is a test file.” > test.txt
    $ cat test.txt
    This is a test
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值