search

Home  >  Q&A  >  body text

utf-8 - python在windows命令行下生成文件乱码问题,如何解决?

编辑一个文件test.py,编码默认是utf-8,代码如下:

print("你好")

命令行下输入:python test.py,显示结果为:你好。
但是当我输入命令:python test.py > test2.py 把输出结果保存到文件,使用编辑器打开test2.py文件是乱码:

在命令行输入type test2.py显示是正常的:

大概直达问题是出在cmd的编码为gbk上,但该怎么解决这个问题?使用:chcp 65001,好像不能解决问题。
谢谢!

阿神阿神2781 days ago721

reply all(5)I'll reply

  • ringa_lee

    ringa_lee2017-04-18 10:22:29

    Use git-bash to search and download one

    reply
    0
  • PHPz

    PHPz2017-04-18 10:22:29

    CMD defaults to gbk, so if the output string is normal, then the output should be GBK characters. First modify the file encoding, and indicate the encoding of the file in the header of the python file, and then write the file and it will be normal

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 10:22:29

    Modify test.py like this,请把编码改为gbk:

    # -*- coding: gbk -*- 
    print('你好')

    reply
    0
  • 阿神

    阿神2017-04-18 10:22:29

    The garbled characters are only related to the encoding of your text editor. You are using Atom. In the lower right corner there is UTF-8 , click and select Chinese (GBK)

    reply
    0
  • PHPz

    PHPz2017-04-18 10:22:29

    Modify cmd default file encoding

    reply
    0
  • Cancelreply