修改文本文件中的字符串

时间:2016-09-09 18:13:53

标签: python python-2.7

我正在使用文本文件存储上次从API中提取数据的时间。

在检查是否应该提取新数据之后,我使用此Python 2.7代码更新最后一个数据点:

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

我希望用这个代码生成的新点替换旧点。我无法弄清楚如何用变量更新splitdata[item]位置。因为splitdata是一个列表,我不能用除整数之外的任何东西来引用这个点。

编辑:

此代码的目标是更新列表splitdata[item]中的splitdata值。问题是我无法使用item作为索引,因为item不是整数。

编辑2:

例如,

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

我正在寻找用新生成的点替换项目

编辑3:

以下是整个方法:

#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

1 个答案:

答案 0 :(得分:1)

您首先要求编辑列表。

有两种方法可以做到这一点:

让计数器知道要编辑的女巫元素:

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

但是你在迭代时编辑列表,这并不总是一个好主意。

根据需要创建输出列表:

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

然后您要求将该列表写入文件。

我认为最好的方法是:

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

完成你的问题。

请考虑以下代码:

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. 在第一部分中,我们创建一个包含每个未更改和新值的新列表。
  2. 然后我们在文件中写下此列表的内容,覆盖已存在的内容(非更新数据)
  3. 我希望这会有所帮助。