Reputation: 192
I have a file that holds the number of each fruit I possess. I then need to edit it every minute to keep it up to date.
apples: 3
bananas: 6
oranges: 12
total: 21 fruits
I want to use python to edit this file. However, I have encountered several problems:
1) I am currently using to following to read/write.
with open(file, 'r') as infile:
# read fruits that I have
infile.close()
with open(file, 'w') as outfile:
while True:
# update data and write to file
outfile.close()
Is there a better/more efficient way (without memory mapping). I tried using f.seek(offset, from_what), but this has issues of its own (if apples goes from 1 digit to 2 digits it throws off the rest of the file).
2) How do I see that it is changing? I tried doing "tail -f" but the way I'm currently editting the file it would append the whole entire new file.
3) When I enter the while look I am constantly editting the file, so anytime I try to cat or vim the file, it is incomplete! Ideally I open the file and I can see the file in its entirety and see it update.
Thanks for reading!
Upvotes: 0
Views: 2080
Reputation: 9220
You can use 'w+' or 'r+' mode to read and write. when you open a file in text mode it's fully buffered by default. To see the live update, you have to flush
every write or open the file in line buffered mode (buffering=1
).
Furthermore, you can't use tail -f
because the file is not appended. To watch the live update, you have to call cat
repeatedly, so watch cat fruits.txt
wil do.
I've simulated your scenario here.
from time import sleep
fruits = dict(apple=1, banana=2, orange=3)
with open('fruits.txt', 'w+', buffering=1) as f:
for _ in range(20):
for fruit, count in fruits.items():
f.write('{}: {}\n'.format(fruit, count))
f.seek(0)
for line in f:
line = line.strip().split(':')
line[1] = int(line[1]) + 1
fruits.update((line,))
f.seek(0)
sleep(1)
Upvotes: 1
Reputation: 1371
Your best option is to read in the file and parse the number of fruits into variables. Then do your math (Add 3 apples or whatever) and then rewrite the file.
You could probably do this best with a dictionary where the keys are your fruit names and the values are the numbers of fruits. Simply write a function that ingests your file and fills out the dictionary, then update the dictionary with your math, then write a function that writes your dictionary to the file in your format you desire. This should be relatively simple.
Upvotes: 0