如何让脚本读写文件?

时间:2017-12-08 23:01:03

标签: python

我从学习Python艰难的方式完成练习16并且它提出了这个问题:

  

编写一个类似于上一个使用readargv的练习的脚本   阅读刚刚创建的文件。

我试图使用'读取'函数以使脚本自动运行并显示脚本创建的文本文件。但是,当我运行所有东西时,没有任何东西出现,它只是一个额外的空白区域,然后关闭它"。如何让它显示任何内容?

from sys import argv

script, filename = argv

txt = open(filename)

print "Erase %r" % filename
print "hit CTRL-C (^C)."
print "hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file."
target.truncate()

print "Need 3 lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "Write these to a file"

target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))

print txt.read()

print "Close it."
target.close()

1 个答案:

答案 0 :(得分:1)

您应该在写完后关闭文件,然后再次打开以阅读:

from sys import argv

script, filename = argv

print "Erase %r" % filename
print "hit CTRL-C (^C)."
print "hit RETURN."

raw_input("?")

print "Opening the file..."
with open(filename, 'w') as target:

    print "Truncating the file."
    target.truncate()

    print "Need 3 lines."

    line1 = raw_input("line 1: ")
    line2 = raw_input("line 2: ")
    line3 = raw_input("line 3: ")

    print "Write these to a file"

    target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))

txt = open(filename)
print txt.read()

print "Close it."
target.close()

第二个版本(没有“with as”结构):

from sys import argv

script, filename = argv

print "Erase %r" % filename
print "hit CTRL-C (^C)."
print "hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file."
target.truncate()

print "Need 3 lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "Write these to a file"

target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))
print "Close it."
target.close()

txt = open(filename)
print txt.read()