错误:在python输出中获取符号

时间:2015-06-02 17:13:49

标签: python python-2.7 text file-io editor

#I wrote the following code for making a text editor.
print "This is a simple text editor"
from sys import argv
script, name = argv
print "You have selected the file : %s" %name
print "Opening the file...."
t = open(name, 'r+')
print "The contents of the file are" 
print t.read()
f = open(name, 'w+')
print "Now we will truncate the file and empty it of it's contents"
f.truncate()
print "Now let us write something into our file\n"
x = raw_input('What do you want to write\n') #Works fine till here
f.write(x)
print "Now we read our file again"
print f.read()
print "And finally we close the file"
f.close()

在提示在文件中写入内容后,脚本出错并生成奇怪的符号而不是键入的文本。请帮忙

1 个答案:

答案 0 :(得分:1)

您需要关闭并重新打开文件。

print "This is a simple text editor"
from sys import argv
script, name = argv
print "You have selected the file : %s" %name
print "Opening the file...."
t = open(name, 'r+')
print "The contents of the file are"
print t.read()
t.close()  ##########
f = open(name, 'w+')
print "Now we will truncate the file and empty it of it's contents"
f.truncate()
print "Now let us write something into our file\n"
x = raw_input('What do you want to write\n') #Works fine till here
f.write(x)
f.close()  ##########
f = open(name, 'r+')  ##########
print "Now we read our file again"
print f.read()
print "And finally we close the file"
f.close()