Peter Hartnett Peter Hartnett - 1 month ago 6x
Python Question

Modifying String in text file Pythton 2.7

So, 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 code:

if pullAgain == True:
lasttimedata = open('lasttimemultiple.txt', 'a+') # open last time again
for item in splitData:
if item[0:2] == PullType:
newTime = PullType + ':' + currenttime #formats the data point
lasttimedata.write(newTime) #trying to write that data point to the spot of the old point.
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 cant figure out how to update the splitdata[item] position with a varible, because split data is a list, I cant reference this spot with anything but an integer.

E: The goal of this code is to update the splitdata[item] value in the list splitdata. the issue is I cant use item as an index, I must use an integer.

E2: 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

Any ideas?


There is two ways for doing what you ask:

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: