2012-04-29 116 views
0

为什么我不能读取我刚刚写入文本文件的内容。该代码不显示任何错误,但我无法阅读我刚写入文档的内容。如果有人能帮我弄清楚这很好。我是新来编程的方式所以请原谅我,如果这是一个简单的疑难问题。现在用Python版本2.6.1无法读取文件

from sys import argv 

script,file_name = argv 
prompt = "> " 

target = open(file_name, 'w+b') 

print "press CRTL-C enter to escape this" 
print "or press RETURN to continue" 

raw_input(prompt) 

print "Begin erasing stuff Goodbye!" 
target.truncate() 

print "we are going to start writing to file" 

write_1 = raw_input(prompt) 
write_2 = raw_input(prompt) 
write_3 = raw_input(prompt) 

target.write(write_1) 
target.write(write_2) 
target.write(write_3) 

print target.read() 


print "closing now!" 
target.close() 

回答

3

你需要做target.seek(0)将文件指针复位到文件的开始在做target.read()之前。

+0

感谢您的帮助。 – Valleyvizor 2012-05-01 06:40:35

2

值得注意的是,打开"w"模式会自动截断文件,因此可能更容易在该模式下打开,写入文件,然后在"r"模式下打开。那是你避免手动截断,寻求回:

from sys import argv 

script, file_name = argv 
prompt = "> " 

print("Press CTRL+C to exit,") 
print("or press RETURN to continue.") 

raw_input(prompt) 

print("Begin erasing.") 
with open(file_name, 'wb') as target: 
    print("Begin writing to file.") 
    write_1 = raw_input(prompt) 
    write_2 = raw_input(prompt) 
    write_3 = raw_input(prompt) 
    target.write(write_1) 
    target.write(write_2) 
    target.write(write_3) 

with open(file_name, "rb") as target: 
    print(target.read()) 

我还使用了the with statementopening files。它不仅更加pythonic和可读,但处理闭幕,即使发生异常。

值得注意的是,目前这可以让您输出所有内容,因为写入不会添加换行符,并且raw_input()不会为您提供导致其继续的换行符。因此,你可能要添加他们,我们也可以只使用一个单一的write()命令与所有的输入串联一个字符串:

print("we are going to start writing to file") 
data = [raw_input(prompt) for _ in range(3)] 
target.write("\n".join(data)) 

这里我用a list comprehension建立输入列表线。这意味着我们不必写出line_x = raw_input(prompt)一个负载的时间,我们可以很容易地改变我们想要使用的行数。这也意味着我们可以很容易地使用str.join()来添加我们想要的换行符。

+0

感谢您的深思熟虑的解释。我几乎没有学习蟒蛇,你解释它像你真的帮助。 – Valleyvizor 2012-05-01 06:40:29