I'm working in 'wb' mode with array of bytes
for i in range(len(mas)):
message.write(mas[i])
after I have to write data to a file on new line, for example '\n' in 'w' mode
for i in range(3):
message.write(str(i))
message.write("\n")
>>>0
>>>1
>>>2
>>>3
How can I do this?
To write a string to a binary file you, like "\n"
into wb
mode, you must first encode it by calling string.encode('utf-8')
or any other encoding you need.
For example, to write a message to a binary file:
with open("a.txt", "wb") as f:
line = str(0) + "\n\n"
f.write(line.encode('utf-8'))
This would write 0\n\n
. To write the numbers from 0 to 3, followed by blank lines:
with open("a.txt", "wb") as f:
for i in range(4):
line = str(i) + "\n\n"
f.write(line.encode('utf-8'))
Encoded newlines are printed as newlines correctly, so the following lines are equivalent:
open('a.txt', 'w').write('\n')
open('a.txt', 'wb').write('\n'.encode('utf-8'))
open('a.txt', 'wb').write(b'\n')
To print a literal \n
, and not a newline, escape the backslash with another backslash \\n
or write r'\n'
to create a "raw" string.
I think you need to write a newline bytestring to your file after each of your bytearrays:
for i in range(len(mas)):
message.write(mas[i])
message.write(b"\n")
Note that a more natural (Pythonic) way of writing your loop is to iterate directly over mas
, rather than iterating on a range and then indexing. You can also combine the two write
calls into one:
for line in mas:
message.write(line + b"\n")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With