我目前在“学习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()

最佳答案

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

filename.seek(0)


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

然后简单地阅读它。

 filename.read()

关于python - 使用相同的脚本进行读写,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33839717/

10-12 21:08