简体   繁体   English

对readline()的理解

[英]Understanding of readline()

I am pretty new to python and found out something that I do not understand about the readline()-function:我对 python 很陌生,发现了一些我对 readline() 函数不了解的地方:

Code 1:代码 1:

f = open("Files/bestTest.txt", "w")
data = f'4\rtest'
f.write(data)
f.close()
f = open("Files/bestTest.txt", "r")
x = float(f.readline())
print(2 * x)
f.close()

The first code works and prints: 8.0第一个代码有效并打印:8.0

Code 2:代码 2:

f = open("Files/bestTest.txt", "w")
data = f'4\rtest'
f.write(data)
f.close()
f = open("Files/bestTest.txt", "r")
print(2 * float(f.readline()))
f.close()

The second code does not work and throws an error: ValueError: could not convert string to float: 'test'第二个代码不起作用并引发错误: ValueError: could not convert string to float: 'test'

I do not understand why the little difference in the code leads to the error.我不明白为什么代码中的微小差异会导致错误。 In the second code readline() seems to also return the second line for some reason.在第二个代码中, readline() 似乎也出于某种原因返回了第二行。 Maybe someone can explain that to me.也许有人可以向我解释。

Thanks in advance提前致谢

I see no reason why your second code should behave differently from the first one since it's literally identical.我看不出为什么您的第二个代码的行为应该与第一个代码不同,因为它实际上是相同的。

The only reason f.readline() has returned the content of the second line is that the cursor is right there at the moment, meaning the first line had already been read during the same session in which the file is open. f.readline()返回第二行内容的唯一原因是 cursor 目前就在那里,这意味着第一行已经在文件打开的同一 session 期间被读取。

readline() reads the lines of a file sequentially so it will return the n -th line, where n is the number of times the function has been called during the same session. readline()顺序读取文件的行,因此它将返回第n行,其中 n 是在同一 session 期间调用 function 的次数。

I suspect you ran the second code without closing and reopening your file.我怀疑您在没有关闭并重新打开文件的情况下运行了第二个代码。 However even if this were the case, you can always return the cursor to the beginning of the file with f.seek(0) .但是,即使是这种情况,您也可以始终使用f.seek(0)将 cursor 返回到文件的开头。

f.seek(0)
print(2 * float(f.readline()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM