read()不读取文件的内容

2024-05-13 19:59:07 发布

您现在位置:Python中文网/ 问答频道 /正文

Python 3代码:

file = open("amdPricesPrices.txt", "a+")
prices = file.read()
print(prices)

文本文件内容:

69.40 69.30 67.61 76.09 78.19 77.67 86.71 84.85

当我执行这段代码时,它只打印一个空行


Tags: 代码txt内容readopenfilepricesprint
3条回答

使用模式"a+"从文件末尾开始读取(和写入)

您需要file.seek(0)到while的开始,或者使用其他打开模式之一:https://stackoverflow.com/a/1466036。如果您只是从文件中读取,则不必指定模式,它将使用"r"的结果

使用+表示附加到文件,而使用r表示读取文件

file = open("amdPricesPrices.txt", "r")
prices = file.read()
print(prices)

如果您想要读写访问(不截断文件)并且文件位于文件的开头,则使用模式'r+'打开,尽管'a+'后面跟file.seek(0)会起作用

相关问题 更多 >