简体   繁体   中英

How to print special characters from a text file

I want to read a text file and print the contents in my windows consol. But special characters are scrambled.

config.txt

[
  {
    "beer": "øl",
    "eel": "ål",
    "egg": "æg"
  }
]

code.py

text = open("config.txt")
print(text.read())

Windows console output python code.py :

[
  {
    "beer": "øl",
    "eel": "Ã¥l",
    "egg": "æg"
  }
]

open() needs to know the enconding of the text file. Change the code to this:

code.py

text = open("config.txt", encoding="utf-8")
print(text.read())

Result when running python, Windows console output python code.py :

[
  {
    "beer": "øl",
    "eel": "ål",
    "egg": "æg"
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM