Im new in python I'm trying to print some chineses word to command line windows 10 and file but got a problem:
Here is my code:
fh = open("hello.txt", "w")
str="欢迎大家加入自由职业者群体。谢谢大家"
print(str)
fh.write(str)
fh.close()
Im new in python I'm trying to print some chineses word to command line windows 10 and file but got a problem:
Here is my code:
fh = open("hello.txt", "w")
str="欢迎大家加入自由职业者群体。谢谢大家"
print(str)
fh.write(str)
fh.close()
The default encoding of files is locale.getpreferredencoding(False)
, which seems to be cp1252
on your system. Specify the encoding when opening the file.
Also use with
and the file will be closed for you when it exits the block:
#!python3.6
with open('hello.txt','w',encoding='utf8') as fh:
str="欢迎大家加入自由职业者群体。谢谢大家"
print(str)
fh.write(str)
To see the Chinese characters on the console you'll need to install a Chinese language pack, and change the console font to one that supports Chinese. Using an IDE that supports UTF-8 will also work. The "boxed question mark" characters are what is displayed when the font doesn't support the characters. If you cut-n-paste those characters to an application like Notepad that has support for Chinese fonts you should see the correct characters.
Here's my US Windows system with the Chinese Language Pack. The console is configured with the SimHei font.
Couple of issues:
There shouldn't be an identation after the fh variable declaration. You shouldn't name a string "str" because that's a builtin function. If you want to use characters outside the latin alphabet you need to declare that you're using UTF-8 like so: # -*- coding: utf-8 -*-
(put that at the top of your file). Then it should work. Although terminal does sometimes have issues with foreign characters.
# -*- coding: utf-8 -*-
fh = open("hello.txt", "w")
str1="欢迎大家加入自由职业者群体。谢谢大家"
print(str1)
fh.write(str1)
fh.close()
Official solution is, use PyCharm!
For me, changing the font in command line worked.
System: Windows 10
Font that worked: NSimSun