Failed to convert file bytes to characters in python3, decode

python3
win10
spyder

fo = open("xingqier.txt","rb")  -sharp :
str = fo.read()  -sharp
str = str.decode("utf-8")   -sharp
str = fo.read(3)  -sharp3
print(":",str)  -sharp

output

: b""

Why not the "first three strings: yesterday" of the output? what"s wrong with the byte conversion characters? How to modify it?

May.05,2022

you read once and the pointer moved to the end. If you keep reading, you won't find the content. You read once to continue reading from the beginning, you need to add a sentence fo.seek (0)
you can read in text mode. Instead of using binary mode and adding the encoding parameter, you don't have to convert bytes to strings.
fo = open ('xingqier.txt','r',encoding='utf-8')-sharp file contents: yesterday was Tuesday
str = fo.read ()
print (str)
fo.seek (0)
str = fo.read (3)-sharp reads the first three characters
print (' first three strings:', str)-sharp prints the first three characters


can directly access the first three characters of str :

fo = open('xingqier.txt','rb')
str = fo.read()
str = str.decode('utf-8')
print(': ', str[:3])

in addition, str is a built-in function of Python and is not recommended as a variable name.

Menu