0

The above notification of a duplicate is false. I do not only want to append to a text file. I also want to delete the oldest parts of the text file so to only keep the latest data.

I have a text file that has some information similar to below.

14.614, 14.624, 14.512, 14.615, etc.

Another number is added every ten minutes. I want to have separate text files that hold the past 365 days, 180 days, 90 days, 60 days, 30 days, 14 days, 7 days and 2 days worth of numbers. The code to do each will be the same, just with different numbers. Here is what I tried, but it adds every new number to the front of the list, not the end.

ff = open('AvailableTickets.txt', 'r').read()
ff2 = ff
ff = ff.replace(',', '')
ff = ff.split()
ff = map(float, ff)
if len(ff) < 10:
    ff3 = open('TestTickets.txt', 'r+')
    ff3.write(str(ff2))
else:
        ff3 = open('TestTickets.txt', 'r+')
        for x in range(0, 10):
            ff3.write(str(ff[len(ff)-x])+', ')
Rontron
  • 3,963
  • 7
  • 26
  • 44
  • possible duplicate of [How do you append to a file in Python?](http://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file-in-python) – zmo Mar 29 '15 at 19:00
  • Not a duplicate. The intent of this post was to find out how to limit a file to only the newest of information, not to all of the information. That would mean appending, but also deleting the old information past a set amount in a list. – Rontron Mar 29 '15 at 19:04

1 Answers1

2

You should open the file in append mode. You should better:

  • use the with statement to correctly close the file and flush it after writing to it,
  • try to avoid unnecessary variable shadowing (ff and ff2),
  • use names that shows what the variables are containing, and finally,
  • use index operator, not range and manual index handling:

with open('AvailableTickets.txt', 'r') as fin:
    tickets_raw = fin.read()
    tickets_list = tickets_raw.split(', ')
    with open('TestTickets.txt', 'a') as f:
        if len(tickets_list) < 10:
            f.write(tickets_raw)
        else:
            f.write(', '.join(tickets_list[-10:]))

then I'm actually wondering what your logic is with the 10 elements checking you're doing, as it does not make a lot of sense to me. It looks to me that depending on how you run this snippet, you might get duplicates.

zmo
  • 24,463
  • 4
  • 54
  • 90
  • The 10 elements was just to see results quickly when I run the script. I will be using 288 for 2 days, 1008 for 7 days, and so on. At the end of your script, tickets isn't defined. I tried it with tickets_list and that worked. – Rontron Mar 29 '15 at 19:03
  • Also, I tried opening TestTickets.txt using append (`a`, but that adds to TestTickets.txt while also duplicating what it previously had. If I open it with read/write (`r+`) it works the way I want it to. – Rontron Mar 29 '15 at 19:15