同一个脚本的阅读和写作

时间:2015-11-21 04:27:00

标签: python python-2.7

我目前正在使用以艰难的方式学习Python 的练习16,我的代码存在问题,它将写入文件,但我的最终打印命令不会打印内容的文件到控制台上。在我的命令行中,它只是出现了几行空格。从我的理解“r +”在读写模式下打开它,但计算机无法读取它。 有人能告诉我它有什么问题吗?任何帮助将不胜感激:)

    from sys import argv
    script, file = argv

    print "The name of the file is %s" % file
    filename = open(file,"r+")

    print "First we must write something in it "
    print "Do you want to continue?Press CTRL-C if not."
    raw_input()

    print "Type the first line of the text"
    line1 = raw_input(">")+"\n"

    print "Type the second line of text"
    line2 = raw_input(">")+"\n"

    print "Type the third line of text"
    line3 = raw_input(">")+"\n"

    sum_line = line1 + line2 + line3

    print "Now I will write it to the file"
    filename.write(sum_line)

    print "The file now says:"

    #This line here does not print the contents of the file
    print filename.read()

    filename.close()

3 个答案:

答案 0 :(得分:2)

如第一个答案中所包含,写入偏移后将指向文件的末尾。但是,您无需关闭该文件并重新打开它。而是在阅读之前这样做:

filename.seek(0)

这将重置文件开头的偏移量。

然后阅读它。

 filename.read()    

答案 1 :(得分:1)

由于您写入了文件,写入后的偏移量将指向文件的末尾。此时,如果您想从头开始阅读该文件,则必须将其关闭并重新打开。

顺便说一句,自Python 2.5以来,支持并建议使用with语句,例如:

with open('yourfile', 'r') as f:
    for line in f:
        ...

使用with将为您关闭文件!

答案 2 :(得分:0)

无需关闭然后重新打开文件,您可以添加filename.seek(0),这会将其恢复到文件的顶部。

filename = open('text.txt',"r+")

print(filename.read())

lin = input()

filename.write(lin)

filename.seek(0) # take it back to top, 0 can be changed to whatever line you want

print(filename.read())

filename.close()