0

I noticed when I execute this command:

comb = open ("out.txt", "r").readlines()[0]
print comb

It will print the first line in the out file and an empty line after it. Why do I have the empty line?

4 Answers 4

4

From the docs:

readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.

You can use this instead:

open("out.txt", "r").read().splitlines()[0]
Sign up to request clarification or add additional context in comments.

Comments

2

Because readlines() reads lines with EOL characters, and print() adds EOL character after printing provided text. EOL - end of line, usually \n.

Comments

1

file.readlines() doesn't strip the newline at the end of each line, and print adds one.

Comments

1

The empty line is there because the line is read as having a '\n' character (newline) at the end of each line. Unfortunately Python doesn't automatically remove this.

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.