Code:
word="hello\nhai"
fout=open("sample.txt","w");
fout.write(word);
Output:
hello
hai
But this:
word=b"hello\nhai"
str_word=str(word) # stripping ' '(quotes) from byte
str_word=str_word[2:len(str_word)-1] # and storing just the org word
fout=open("sample.txt","w");
fout.write(str_word);
Outputs:
hello\nhai
What is the problem in the code?
I am working on sending and receiving strings over a port in python. As only bytes can be sent and received I have the above problem. But why does it occur?
Write the bytes in binary mode:
word=b"hello\nhai"
with open("sample.txt","wb") as fout:
fout.write(word);
You can also encode the original string to bytes:
word="hello\nhai".encode()
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.