Reputation: 823
It says that my file is not open to read the file entered, but it is because target = open(textname) What's wrong?
from sys import argv
filename, textname = argv
target = open(textname, "w")
print "Do you want to truncate %r?" % textname
raw_input("PRESS RETURN KEY IF YES")
target.truncate()
print "What would you like to type now?"
line1 = raw_input("Line 1--> ")
target.write(line1)
target.write("\n")
line2 = raw_input("Line 2--> ")
target.write(line2)
target.write("\n")
line3 = raw_input ("Line 3--> ")
target.write(line3)
target.write("\n")
print target.read()
THANK YOU!
Upvotes: 0
Views: 252
Reputation: 2393
First change the file open mode to r+
(or w+
), and then add one line target.seek(0,0)
before you try to print the content.
from sys import argv
filename, textname = argv
target = open(textname, "r+")
print "Do you want to truncate %r?" % textname
raw_input("PRESS RETURN KEY IF YES")
target.truncate()
print "What would you like to type now?"
line1 = raw_input("Line 1--> ")
target.write(line1)
target.write("\n")
line2 = raw_input("Line 2--> ")
target.write(line2)
target.write("\n")
line3 = raw_input ("Line 3--> ")
target.write(line3)
target.write("\n")
target.seek(0,0)
print target.read()
You can check the seek
method in another answer in Stackoverflow for more information.
Upvotes: 4
Reputation: 238071
I think the best way would be two first open file for writing, and then when you are done with it, open for reading. For me personally, its not very natural for a file to be open for writing and reading at the same time. Usually I tend to have the file either open for writing or reading. Here you can find more info how to read and write files the same time.
from sys import argv
filename, textname = argv
print "Do you want to truncate %r?" % textname
raw_input("PRESS RETURN KEY IF YES")
print "What would you like to type now?"
with open(textname, "w") as target:
line1 = raw_input("Line 1--> ")
target.write(line1)
target.write("\n")
line2 = raw_input("Line 2--> ")
target.write(line2)
target.write("\n")
line3 = raw_input ("Line 3--> ")
target.write(line3)
target.write("\n")
with open(textname, "r") as target:
print target.read()
Upvotes: 2
Reputation: 881113
target = open(textname, "w")
:
print target.read()
What do you think it should do when you've told it to open the file as write-only?
If you want to be able to both read and write, use the r+
mode (you can also use w+
but that will truncate the file regardless).
Upvotes: 2