Answer the question
In order to leave comments, you need to log in
Why does encoding break in Python?
I want to truncate a text file to 7 characters.
As long as the text file is in Latin, everything goes well:
#vsem privet
x=open("hello.txt","r+",encoding="utf-8")
x.truncate(7)
#vsem pr
#всем привет
x=open("hello.txt","r+",encoding="utf-8")
x.truncate(7)
#все
Answer the question
In order to leave comments, you need to log in
Well, for starters, files in Python are opened via the with ... as construct.
And if there are problems with the encoding, everyone runs to the deity named io.open
Python3
with io.open("hello.txt", "r", encoding="utf-8") as f:
s = f.read() # в строке будут декодированные кириллические символы
print( s )
print( s[:7] ) # используем срез
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question