Reputation: 31
Why does the second call of:
num_lines = len(file.read().split("\n")) - 1
return 0 instead of the correct value?
with open("Data.txt", "r+") as file:
num_lines = len(file.read().split("\n")) - 1
print("Old num_lines: " + str(num_lines))
# Add 10 new lines of data to end of the file
for i in range(num_lines, num_lines + 10):
file.write("{}, {}\n".format(i, random.randint(0, 10)))
num_lines = len(file.read().split("\n")) - 1
print("New num_lines: " + str(num_lines))
Upvotes: 3
Views: 158
Reputation: 7490
Reading a file is like reading a book, in which you have a bookmark that you move as you progress in reading.
When you open a file you have that "bookmark" in initial position, and after reading some of its parts it is moved in order to remember the next bytes to be read.
Your second
num_lines = len(file.read().split("\n")) - 1
is in the same block of all the other reads, after the whole file was read. The "bookmark" is already at the end of file.
Instead of re-reading the file I suggest saving the initial number of lines at the first read:
old_num_lines = num_lines = len(file.read().split("\n")) - 1
Anyway going back to the beginning of the file would be very simple as well, through seek()
method:
file.seek(0)
Upvotes: 2
Reputation: 12523
You open the file once (with open("Data.txt", "r+") as file
). You read a bunch of stuff, which changes your current position in the file. The first 'read' operation sets the position at the very end of the file.
You then write something, which continues to move the current position to the end of the file.
Finally, you do another file.read()
. This means 'read N bytes starting the current position in the file'. Since the current position is the very end of the file, you read nothing.
Have a look at the formal documentation for more details.
Upvotes: 0
Reputation: 6027
You read the file once, you cannot read it again, the seek has reached the end of the file.
You need to seek to start of the file.
file.seek(0)
Before trying to read the file again.
On a side note, you don't need to read the file again. If you are adding 10 lines to the file in your code, the new number of lines would be:
num_lines += 10
Upvotes: 1