fhand = open("text.txt") for line in fhand: print(line) 

In the text.txt file the word " hello ". When you run the script, the output in the console: " R ± P" С‚С, С ". Cyrillic is displayed normally in the terminal itself. Also, the usual print (' Hello ') command displays " Hello " in the terminal. Why does the encoding break when reading Cyrillic from a file, and how can I fix it? UTF-8 terminal encoding

  • It matters in what encoding the text is stored in the file. For example, under windows, the open function will attempt to open a file encoded in win1251. If your file is saved in a different encoding, then reading from the file you will receive not what you wanted to see. It is necessary to clarify in what encoding the file is saved, and when opening the file, specify it: fhand = open("text.txt", encoding='utf-8') - insolor
  • @insolor Thanks, helped. Is it possible to somehow specify the encoding once, for example at the beginning of the file. In the event that you need to open a lot of files? - kurmark kurmark
  • I do not see a problem in each time specifying the encoding explicitly ("explicit better than implicit"). Theoretically, the default encoding can be changed, but now I did not immediately find out how (you can find out through locale.getpreferredencoding() ). - insolor

0