I am trying to create a database to store the information generated by my code in the form of a 1 x 21 vector. I have called this prices
, and would like to store each element of this vector in a new line of a text file. Then, the second time I run the program, I wish to append the new entries of the vector prices
onto each respective line in the text file. The purpose of this is so that once a large set of results has been gathered, it is easy to produce a plot to see how each of these 21 elements changed over time.
I tried to copy (with a bit of modification with the condition in the if loop, as well as the overall for loop) the method shown in this answer, but for some reason, I get a blank text file when I run the code. I changed one thing, the w
to w+
, but it doesn't work with the w
either. What am I doing wrong?
prices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1] # this is just a sample output
for exp in range(21):
with open("price_database.txt", 'r') as f:
lines = f.readlines()
with open("price_database.txt", 'w+') as f:
for x, line in enumerate(lines):
if x == exp:
f.write(str(prices[exp]))
f.write(line)
Edit 1:
prices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]
for exp in range(21):
with open("price_database.txt", 'r') as f:
lines = f.readlines()
with open("price_database.txt", 'a') as f:
for x, line in enumerate(lines):
if x == exp:
f.write(str(prices[exp]))