(Python) 无法打印文本文件的所有内容

(Python) Can't Print all the Contents of the Text File

我已尽力打印我的文本文件的所有内容。但我仍然无法理解哪里出了问题。这是我的代码:

Input = input("TYPE: ")

with open("tryme.txt","a+") as f:
    f.write(Input + "\n\n\n" )

    x = f.read()
    print(x)

my codes and text file

a+ Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.

您应该使用 f.seek() 将文件偏移量设置为文件的开头。

with open("tryme.txt","a+") as f:
    f.write(Input + "\n\n\n" )
    f.seek(0)
    x = f.read()
    print(x)

输出:

TYPE: test2
test1


test2

希望对您有所帮助。

写入文件后,reader的当前位置在文件末尾。如果要读取整个文件,需要return到开头。

尝试

Input = input("TYPE: ")

with open("tryme.txt","a+") as f:
    f.write(Input + "\n\n\n" )
    f.seek(0,0)
    x = f.read()
    print(x)