简体   繁体   中英

Understanding of readline()

I am pretty new to python and found out something that I do not understand about the readline()-function:

Code 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

Code 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'

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. 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.

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.

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)
print(2 * float(f.readline()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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