无法获取文件输出内容

cur*_*wag -1 python io

所以我试图让我的python程序接受用户的文件,然后截断文件,向其添加内容,输出文件,最后关闭.问题是它不会输出.我已经在写入+读取模式下打开文件,但文件不会输出target.read().这是我的源代码.问题是从底部开始的第三行.

    from sys import argv

    script, filename = argv

    print "We're going to erase %r." %filename
    print "If you don't want that, hit CTRL-C."
    print "If you do want that, hit RETURN."

    raw_input("?")

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

    print "Truncating the file. Good bye!"
    target.truncate()

    print "Now I'm going to ask you for three lines."

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

    print "I'm going to write these to a file."

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

    print "And now we get to read the file."
    print target.read()
    print "And finally, we close it."
    target.close()
Run Code Online (Sandbox Code Playgroud)

我正在Mac上运行终端,运行python 2.7.这是我的输出.

    We're going to erase 'test2.txt'.
    If you don't want that, hit CTRL-C.
    If you do want that, hit RETURN.
    ?
    Opening the file...
    Truncating the file. Good bye!
    Now I'm going to ask you for three lines.
    line 1: asd
    line 2: zxcz
    line 3: qwe
    I'm going to write these to a file.
    And now we get to read the file.

    And finally, we close it.
Run Code Online (Sandbox Code Playgroud)

底部的第二行是输出应该是的位置.什么时候cat用于输出文件,它有它应该的内容.请让我知道我做错了什么.

ssh*_*124 8

在此之前,target.read()您希望seek通过执行以下操作来启动文件:

target.seek(0)
Run Code Online (Sandbox Code Playgroud)

如果您不寻求文件的开头,文件"cursor"将位于文件的末尾,因此当您尝试阅读时,您将什么也得不到.这是因为当你写,光标前进.

有用的资源