pranav
pranav

Reputation: 460

Python : Printing contents of a file to the terminal

I am a newbie to Python and was reading up about files from the Python Tutorial

So , I made a small program to practice file handling :

from sys import *

script , file_name = argv

print "Your file is : %s" %file_name

print "Opening the file..."
temp = open(file_name, 'r+')

print "Truncating the file "
temp.truncate()

print "Enter three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "Writing these to the file."

temp.write(line1)
temp.write("\n")
temp.write(line2)
temp.write("\n")
temp.write(line3)
temp.write("\n")


#for line in temp:
       #print line
#temp.read()

print "Closing it."
temp.close()

My Question:

Somehow I am not able to print the content of the file to the terminal using either of the commented (#) statements in the code above . Can someone help me out ?

Upvotes: 1

Views: 1056

Answers (2)

Aaron
Aaron

Reputation: 2393

You can add a line

temp.seek(0,0)

before

for line in temp:
    print line
temp.read()

Thus set the pointer to the beginning of the file again.
For more information about seek(), see https://stackoverflow.com/a/11696554/1686094

Upvotes: 2

WakkaDojo
WakkaDojo

Reputation: 431

When you're appending to the file, python is reading from where your "cursor" is in the file, which is at the end.

You need to close the file and open it as "r", and then you will be able to index the contents from the beginning.

Upvotes: 3

Related Questions