Write python file with various asci codes
Question:
I would like to write a python file containing four bytes:
- A space
- A tab
- A carriage return
- A newline
I’m not able to write it as:
open('file.txt', 'w').write(' trn')
As for whatever reason it’s converting the r
into a n
. How would I then write this as the asci codes themselves? that is:
NEWLINE = 10
CARRIAGE = 13
SPACE = 32
TAB = 9
open('file.txt','wb').write(bytearray([SPACE, TAB, CARRIAGE, NEWLINE]))
Answers:
Open the file in binary mode and write a byte string.
open('file.txt', 'wb').write(b' trn')
I would like to write a python file containing four bytes:
- A space
- A tab
- A carriage return
- A newline
I’m not able to write it as:
open('file.txt', 'w').write(' trn')
As for whatever reason it’s converting the r
into a n
. How would I then write this as the asci codes themselves? that is:
NEWLINE = 10
CARRIAGE = 13
SPACE = 32
TAB = 9
open('file.txt','wb').write(bytearray([SPACE, TAB, CARRIAGE, NEWLINE]))
Open the file in binary mode and write a byte string.
open('file.txt', 'wb').write(b' trn')