Peter Hartnett Peter Hartnett - 2 months ago 7
Python Question

Modifying string in a text file

I am using a text file to store the last time data was pulled from an API.

After I check if new data should be pulled I am updating the last datapoint with this Python 2.7 code:

if pullAgain == True:
# open last time again
lasttimedata = open('lasttimemultiple.txt', 'a+')
for item in splitData:
if item[0:2] == PullType:
#formats the data point
newTime = PullType + ':' + currenttime
#trying to write that data point to the spot of the old point.
lasttimedata.write(newTime)
print('We updated the last time')

lasttimedata.close() # close last time


I'm looking to replace the old point with the new point that this code generates. I can not figure out how to update the
splitdata[item]
position with a variable. Because
splitdata
is a list I can not reference this spot with anything but an integer.

EDIT:

The goal of this code is to update the
splitdata[item]
value in the list
splitdata
. The issue is I can not use
item
as an index because
item
is not an integer.

EDIT 2:

For example,

splitdata = ['00:23:15:42','01:15:12:54','02:12:23:54']


I'm looking to replace the item with the newly generated point

EDIT 3:

Here is the whole method:

#Pull type is the piece of data being pulled,
# capability to Have 99 types, current default is 00.
def PullAgain(PullType):

# This is the variable that decides if the API is called
# again, True = pull data again.
pullAgain = False

# Calls the local time
s1=time.localtime()

#takes the hours, minutes and seconds out of the time
currenttime = str(s1[3])+':'+str(s1[4])+':'+str(s1[5])

#opens the file that contains the last time run
timefile = open('lasttimemultiple.txt','r+')

#reads the last time file
rawfile = timefile.read()

#splits the string into each individual row
splitData = string.split(rawfile,'\n')

#closes last time
timefile.close()
lasttime = "05:06:12"

for item in splitData:
if item[0:2] == PullType:
lasttime = str(item[3:])
print('We made it into the if statement')

print lasttime

#this is the time formatting
FMT = '%H:%M:%S'

#calculates the difference in times
delta = (
datetime.strptime(currenttime, FMT) -
datetime.strptime(lasttime, FMT))

#converts the difference into a string
tdelta = str(delta)
print 'this is tdelta before edit:',tdelta

if tdelta[0] =='-':
tdelta = tdelta[8:]
print 'tdelta time has been adjusted', tdelta

#if more than 0 hours apart
if int(tdelta[0])>0:
#Then call api again
pullAgain = True
elif int(tdelta[2])>=3:
#if time is greater than 29 sec call api again
pullAgain = True
else:
pullAgain = False
print('New data not pulled, the time elapsed since last pull was: '),tdelta

splitData2 = []

if pullAgain == True:
# open last time again
lasttimedata = open('lasttimemultiple.txt', 'a+')
for item in splitData:
if item[0:2] == PullType:
newTime = PullType + ':' + currenttime
splitData2.append(item)
lasttimedata.write(splitData2)
print('We updated the last time')

lasttimedata.close() # close last time

return pullAgain#return the decission to pull again or not

Answer

You were first asking for editing a list.

There is two ways for doing that:

Keep a counter to know witch element to edit:

for index, item in enumerate(splitData):
    splitData[item] = new_value

But your are editing the list while iterating, and that is not always a great idea.

Create an output list will the element you want:

output_list = []
for item in splitData:
    if i_want_to_keep:
        output_list.append(item)
    else:
        output_list.append(new_value)

Then you are asking to put write that list in a file.

I think that the best way of doing it is:

with open(filename, 'w') as f:
    for element in my_list:
        f.write(element)

To finish with your question.

Please consider this code:

splitData2 = []
if pullAgain == True:
    # Change in splitData all the times that need to be update
    for item in splitData:
        newTime = PullType + ':' + currenttime
        if item[0:2] == PullType:
            splitData2.append(newTime)
            print('We updated the last time')

    # ReWrite the whole file with the whole data from splitData2
    with open('lasttimemultiple.txt', 'w')  as f:
        for item in splitData2:
            f.write(item)
  1. In the first part we create a new list that contain every non-changed and new values.
  2. Then we write the content of this list in the file overwriting what was already there (the non-updates datas)

I Hope that is going to help.