Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write on new string uses byte 'wb' mode?

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?

like image 956
False Promise Avatar asked Jun 26 '14 00:06

False Promise


2 Answers

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.

like image 67
BoppreH Avatar answered Oct 11 '22 20:10

BoppreH


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")
like image 24
Blckknght Avatar answered Oct 11 '22 21:10

Blckknght