[英]Python: Why does it say that my file is not open to read it?
It says that my file is not open to read the file entered, but it is because target = open(textname) What's wrong? 它说我的文件没有打开才能读取输入的文件,但这是因为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()
THANK YOU! 谢谢!
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. 首先将文件打开模式更改为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()
You can check the seek
method in another answer in Stackoverflow for more information. 您可以在Stackoverflow的另一个答案中检查seek
方法, 以获取更多信息。
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). 如果您希望能够读取和写入,使用r+
模式(你也可以使用w+
,但将截断该文件,而不管)。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.