简体   繁体   中英

Creating, then appending data on to the end of each line on a text file in python

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]))

You need to close the file every time you open to read or write results with f.close() but i cant undertand why you use txt file to do this job you should really use csv or even mysql it will be much better

Edited: Open the file with append mode so you can write at the end:

with open('something.txt', 'a') as f:
    f.write('text to be appended')
    f.close()

If you want to be a little less careful, then do it this way, it is slightly faster because you don't have to keep closing.

app = 'append text'
with open('something.txt', 'a') as f:
    f.write(app)
f.close()

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