0
def read_text():
    quotes = oepn("C:\Python27\houston.txt")
    contents_of)file = quotes.read()
    print(contents_of_file)
    quotes.close()
read_text()

The code above is well working in my shell I guess you can run it too. ("C:\Python27\houston.txt") is the place where txt stored, and it tells this.... -- Houston, we have a problem. (Apollo 13)

-- Mama always said, life is like a box of chocolates. You never know what you are going to get. (Forrest Gump)

-- You cant handle the truth. (A Few Good Men)

-- I believe everything and I believe nothing. (A Shot in the Dark)

whatever, I just give it little difference in my code, but it doesn't work.

I don't know why ;;; check this plz

quotes = open("C:\Python27\houston.txt")
contents_of_file = quotes.read()
print(quotes.read())
quotes.close()

see... I only replace contents_of_file with quotes.read() but it doesn't work. can you tell me why??? why this happen?

Rosemol J
  • 183
  • 4
  • 19
dante
  • 933
  • 4
  • 16
  • 39
  • Why are you calling `quotes.read()` twice? Doing it once gets the entire content of the file as a string. I don't understand what you are doing. – idjaw Mar 09 '16 at 06:09
  • Your "working" code has typos. Please copy and paste the actual working code next time. – TigerhawkT3 Mar 09 '16 at 06:14

1 Answers1

0

When you call quotes.read(), it reads the entire file and places the cursor at the end of the file. So, at the second call, it starts reading from the end of the file, clearly you will get nothing.

You can call quotes.seek(0) to place the cursor at the start of the file again. Then calling quotes.read() again will work.

When you are printing contents_of_file, it works, because you already had the whole content of the file as a string in that variable.

But, when you are printing quotes.read(), you are basically calling quotes.read() twice. So, you are getting nothing.

So, if you really want to call read() twice, do:

quotes = open("C:\Python27\houston.txt")
contents_of_file = quotes.read()
quotes.seek(0)
print(quotes.read())
quotes.close()
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
  • this is what I''ve been looking for! thank you for sharing your precious knowledge for beginner. – dante Mar 10 '16 at 02:14