0

ip.txt

127.0.0.1
127.0.0.10
127.0.0.15

Code

user@linux:~$ cat script01.py 
with open('ip.txt', 'r') as f:
    for line in f:
        print(line)
user@linux:~$ 

Output

user@linux:~$ python script01.py 
127.0.0.1

127.0.0.10

127.0.0.15
user@linux:~$ 

One of the solution provided to remove additional new line was to use sys.stdout.write instead of print

Python is adding extra newline to the output

New code with sys.stdout.write

user@linux:~$ cat script02.py 
import sys

with open('ip.txt', 'r') as f:
    for line in f:
        # print(line)
        sys.stdout.write(line)
user@linux:~$ 

However, sys.stdout.write delete the last line.

user@linux:~$ python script02.py 
127.0.0.1
127.0.0.10
127.0.0.15user@linux:~$ 

How to fix this problem?

2 Answers 2

1

Use

with open('ip.txt', 'r') as f:
    for line in f:
        print(line, end='')
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the function strip() to remove the line break:

with open('ip.txt', 'r') as f:
    for line in f:
        print(line.strip("\r\n"))

The argument "\r\n" makes the function to only delete all newlines and carriage returns at the beginnig and end of the line. Without that argument it would also delete spaces and tabs at the beginning and end what you might not want.

2 Comments

Thanks @Sadap. print(line.strip()) also produce similar output
Yes, the output is similar as long as you don't have spaces or tabs at the beginning or at the end

Your Answer

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