Python:示例16学习艰难的方法

时间:2016-01-10 05:06:22

标签: python

我做了示例16,并决定继续添加它。我想在重写内容之后能够立即阅读它。

from sys import argv

script, file = argv

print "Do you want to erase the contents of %r?" % file
print "If yes hit RETURN, or CTRL-C to abort."

raw_input()

target = open(file, 'w')

target.truncate()

print "Now you can type new text to the file one line at a time."

line1 = raw_input("line1: ")
line2 = raw_input("line2: ")
line3 = raw_input("line3: ")

print "The data will now be written to the file."

target.write(line1)
target.write('\n')
target.write(line2)
target.write('\n')
target.write(line3)
target.write('\n')

print "Data has been added to the file."

new_data = open(target)

print new_data.read()

在我到达这一点后运行它后,我得到语法错误需要字符串缓冲区,找到文件。我从一开始就知道这个文件是在' w' (写模式)所以我也尝试了这个:

new_data = open(target, 'r')

print new_data.read()

3 个答案:

答案 0 :(得分:1)

如果您要同时读取和写入文件,请使用适当的模式,例如'w+',类似于'w',但也允许阅读。我还建议使用with上下文管理器,这样您就不必担心关闭文件了。您也不需要truncate(),如this question中所述。

with open(file, 'w+') as target:
    # ...your code...

    # new_data = open(target) # no need for this
    target.seek(0) # this "rewinds" the file
    print target.read()

答案 1 :(得分:0)

答案在错误消息中,您试图将文件传递给open()函数,而第一个参数应该是一个字符串 - 文件名/路径到文件。 这假设起作用:

new_data = open(file, "r")
print new_data

答案 2 :(得分:0)

更优选使用"开放资源作为"语法,因为它会自动刷新并关闭在写入文件之后需要执行的资源,然后才能从中读取(没有seek - 文件的开头)。

print "Do you want to erase the contents of %r?" % file
print "If yes hit RETURN, or CTRL-C to abort."

raw_input()

with open(file, 'w+') as target:

    target.truncate()

    print "Now you can type new text to the file one line at a time."

    line1 = raw_input("line1: ")
    line2 = raw_input("line2: ")
    line3 = raw_input("line3: ")

    print "The data will now be written to the file."

    target.write(line1)
    target.write('\n')
    target.write(line2)
    target.write('\n')
    target.write(line3)
    target.write('\n')

print "Data has been added to the file."

with open(file) as new_data:
    print new_data.read()