它说我的文件没有打开来读取输入的文件,但这是因为target = open(textname) 怎么了?
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()
谢谢!
答案 0 :(得分:4)
首先将文件打开模式更改为r+
(或w+
),然后在尝试打印内容之前添加一行target.seek(0,0)
。
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()
您可以查看another answer in Stackoverflow中的seek
方法以获取更多信息。
答案 1 :(得分:2)
target = open(textname, "w")
:
print target.read()
当你告诉它以只写方式打开文件时,你认为它应该做什么?
如果您希望能够同时阅读和,请使用r+
模式(您也可以使用w+
,但无论如何都会截断文件。)< / p>
答案 2 :(得分:2)
我认为最好的方法是两个第一个用于写作的打开文件,然后当你完成它时,打开阅读。就我个人而言,同时打开文字和阅读文件并不是很自然。通常我倾向于打开文件进行书写或阅读。在这里,您可以找到有关如何读取和写入文件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()