def replace_line(file_name, line_num, text): lines = open(file_name, 'r').readlines() lines[line_num] = text out = open(file_name, 'w') out.writelines(lines) out.close() replace_line('filename.py',200, 'Что-то на русском') 

The file writes. Utf-8 file encoding

  • 3
    1 - check that open opens the file with utf-8 encoding (for Windows, by default, it will most likely open with cp1251 encoding). Accordingly, the file should be opened with the utf-8 encoding. 2 - maybe your text editor (or what you open the finished file with) does not support utf-8. Or by default in it other coding is selected. Or the file encoding (source and finished) is different. - insolor

2 answers 2

Second line:

 lines = open(file_name, 'r', encoding='utf-8').readlines() 

Try this, on Windows, the encoding is usually cp1251

    Thank you, problem solved. Replaced these lines

     lines = open(file_name, 'r', encoding='utf-8').readlines() out = open(file_name, 'w',encoding="utf-8")