doubl00
doubl00

Reputation: 3

How do I read a text file line-by-line the "Pythonic" way

I realize this is a common and simple question that has been asked before. I was able to complete my project using a pseudo C method from the following post by dawg. I used a 'while True' and tested for a blank line.
read a text file line by line.

The IDE warns the local variable line is not used. Changing variable s to line had not effect on the output. But the Pytonic way suggested by dawg seemed to skip lines. I have taken out all the processing I performed in the method (text to int, putting data into a list of tuples, and sorting it) and I rewrote the text file for this post. Similar results.

I also did try sys.stdin suggestion but do not have those results saved.

Obviously, I am a beginner with Python3.5.

# iofile_test3.py

with open('test_read_file.txt', 'r') as f:
for line in f:
    # read a line from file
    s = f.readline()
    print(s)


#test_read_file,txt
First line
Second line
Third line
Fourth and last line

######output#####
.Python 3.5.2 (default, Sep 14 2017, 22:51:06) 

`>>>

Second line

Fourth and last line


>>> 

I am using Pycharm 17.3 Community version but also tried this code with Idle with the same output. Lines 1 and 3 seem to be skipped. My OS is Linux Mint.

Upvotes: 0

Views: 142

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126526

The lines are skipped because you're throwing them away without printing them. The usual way would be to not ignore them:

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

Upvotes: 2

Related Questions