0

I wrote a script in Python and I ran it in the command line. The first part of the output is what I had expected it to be. However, it does not print the first line as I want it to with readline(). I am asked the second question but when I answer "yes" it prints an empty line. When I remove the if statement and the first question it works fine, but I can't get it to work with the if statement. Here's the script:

script, filename = argv

print("I'm going to open the file.")
txt1 = open(filename) 
question1 = raw_input("Do you wanna see the content? ")


if (question1 == "yes" or question1 == "Yes"):
   print(txt1.read())

question2 = raw_input("Do you want me to read just the first line? ")
if (question2 == "yes" or question2 == "Yes"):
   print(txt1.readline())

Thanks in advance.

  • 1
    https://docs.python.org/2/tutorial/inputoutput.html <-- Once you read() from file the cursor is set to the EOF. You will have to re-open() file to be able to read something from the beginning. – GSazheniuk Apr 27 '18 at 21:19
  • 1
    @GSazheniuk Great answer! Make sure to point this out in the answer next time,as this is the correct answer, or this time and I'll make sure to upvote. Take care! – innicoder Apr 27 '18 at 21:21
  • You probably should use txt1.readline() rather than .read(); the latter "slurps" in the whole file while the other reads a line at a time. So, read in the first line; save it. read the rest, concatenate those to show all contents and display just the saved first line if the response to the second question is affirmative. – Jim Dennis Apr 27 '18 at 21:23
  • Like others have already said, files are stateful and there's nothing left to read after your first `file.read()` call. You either have to re-open the file, or reset the file cursor to the beginning with `file.seek(0)`. Or store the content of the file in a variable and use that for your prints. – Aran-Fey Apr 27 '18 at 21:25

2 Answers2

1

The file object returned by open() keeps track of where in the file you are. The first call you make to txt1.read() reads the whole file and advances your position in the file to the end. If you want to reset back to the beginning of the file, you can do txt1.seek(0) before reading from the file again.

lemoncucumber
  • 133
  • 1
  • 5
1

You might want to do

txt1.seek(0)

between the two reads. This resets your current position to the start of the file.

Better style would be

if (question1 == "yes" or question1 == "Yes"):
    with open(filename) as txt1:
        print(txt1.read())
mdurant
  • 27,272
  • 5
  • 45
  • 74