Reputation: 19
Hey! I am getting a problem with my script.
I wrote it when reading LPTHW book.
I am not getting an error message but I am not getting the correct output, I think there might be a setting wrong with my system. I am confused.
Here is the script:
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w+')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1= raw_input("line1: ")
line2= raw_input("line2: ")
line3= raw_input("line3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "Now, I am going to read the file"
print target.read()
print "And finally, we close it."
target.close()
and here is the output:
PS C:\Users\Isaac\lpthw> python ex1.py sample.txt
We're going to erase 'sample.txt'.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line1: i
line2: love
line3: mo
I'm going to write these to the file.
Now, I am going to read the file
#☻ ` ▬☻ ` ▬☻ .☻
Upvotes: 1
Views: 252
Reputation: 175605
When you call target.write()
, the file pointer is left just after the written data. You can call target.tell()
to see where it is:
>>> target.tell()
0
>>> target.write('hello')
>>> target.tell()
5
You need to seek to the beginning of the file before you read it:
target.seek(0)
print target.read()
Upvotes: 6