Insiyah_Hajoori
Insiyah_Hajoori

Reputation: 89

What is the mistake i'm making?

I'm learning python from Learn Python The Hard Way. This is one of the exercises given, but my output doesn't matches the What You Should See section. Here is the output snap. The 2nd line is printed in number 3 and the 3rd line isn't printed at all.

Here is my code:

from sys import argv 

script, input_file = argv 

def print_all(f):    
    print f.read() 

def rewind(f):   
    f.seek(0)

def print_a_line(line_count, f):    
    print line_count, f.readline()     

current_file = open(input_file)     
print "First let's print the whole file:\n"

print_all(current_file)    

print "now let's rewind, kind of like tape."

rewind(current_file)

print "Let's print three lines: "

current_line = 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)

Is there some problem with readline() in my system? This isn't the first time this happens.

Upvotes: 1

Views: 94

Answers (1)

user6547518
user6547518

Reputation:

Your test.txt file contains several blank lines. You have to delete them, particularly between line1 and line2. It will solve your problem.

Without empty line :

First let's print the whole file:

this is line1.Say hello.
this is line2. This must be printed!!
this is line3.This is cool!Print please

now let's rewind, kind of like tape.
Let's print three lines: 
1 this is line1.Say hello.

2 this is line2. This must be printed!!

3 this is line3.This is cool!Print please

In your case (with empty line), you simply print the empty line starting with "2" (which means that the global variable current_line is effectively incremented):

First let's print the whole file:

this is line1.Say hello.

this is line2. This must be printed!!

this is line3.This is cool!Print please

now let's rewind, kind of like tape.
Let's print three lines: 
1 this is line1.Say hello.

2 

3 this is line2. This must be printed!!

Upvotes: 1

Related Questions