2

I run the following code with Python 3.5.1 on Windows 7.

with open('foo.txt', 'wb') as f:
    print(b'foo\nbar\n', file=f)

I get the following error.

Traceback (most recent call last):
  File "foo.py", line 2, in <module>
    print(b'foo\nbar\n', file=f)
TypeError: a bytes-like object is required, not 'str'

My intention is to write text in a file such that all '\n' appears as LF (as opposed to CRLF) in the file.

What's wrong in my code above? What is the right way to write text into a file opened in binary mode?

2 Answers 2

2

You don't need binary mode. Specify the newline when opening the file. The default is universal newline mode, which translates newlines to/from the platform default. newline='' or newline='\n' specifies untranslated mode:

with open('foo.txt', 'w', newline='\n') as f:
    print('foo', file=f)
    print('bar', file=f)

with open('bar.txt', 'w', newline='\r') as f:
    print('foo', file=f)
    print('bar', file=f)

with open('foo.txt','rb') as f:
    print(f.read())

with open('bar.txt','rb') as f:
    print(f.read())

Output (on Windows):

b'foo\nbar\n'
b'foo\rbar\r'
Sign up to request clarification or add additional context in comments.

4 Comments

That is going to CRLF on Windows instead of writing LF. I want LF to be written even on Windows.
@LoneLearner did you try it? Python 3 does it's own line handling and it writes only LF on Windows with this code. I'm on Windows and verified it with a hex dump.
@LoneLearner Added proof.
@MarkTolonen Thank you so much this really helped me :).
0

print() does things to the object passed to it. Avoid using it for binary data.

f.write(b'foo\nbar\n')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.