user9013730
user9013730

Reputation:

Python3 sys.stdout.write delete last line

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?

Upvotes: 0

Views: 277

Answers (2)

bb1950328
bb1950328

Reputation: 1599

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.

Upvotes: 0

Niranjan Kumar
Niranjan Kumar

Reputation: 1518

Use

with open('ip.txt', 'r') as f:
    for line in f:
        print(line, end='')

Upvotes: 1

Related Questions