我真的很新的python和尋找一些幫助。我對目前的數據的文本文件:python:檢查然後更新文本文件中的值
Tue Jun 25 **15** 336 0 0 0 0 0
Tue Jun 25 **04** 12682 0 0 0 0 0
Tue Jun 25 **05** 12636 0 0 0 0 0
Tue Jun 25 **06** 12450 0 0 0 0 0
Tue Jun 25 **07** 12640 0 0 0 0 0
我想通過每一行,並檢查是否是大於12,如果大於12,我想從中減去12然後回寫給新的號碼。
下面就是代碼,我到目前爲止有:
infile = open("filelocation", "a+") #open the file with the data above and append/ open it
def fun (line, infile): # define a function to to go to position 12 - 14 (which is where the date in bod is) and set it to an integer
t = infile[12:14]
p = int(t)
if p > 12: # here is the logic to see if it is greater then 12 to subtract 12 and attempt to write back to the file.
p = p - 12
k = str(p)
infile.write(k)
else:
print p # probably not needed but i had it here for testing
return
# I was having an issue with going to the next line and found this code.
for line in infile:
print line, infile
line = fun(line, infile.next())
break
infile.close()
的主要問題是它不是通過每個迭代線或進行更新。甚至可能有更好的方法來做我想做的事情,只是沒有知識或者不瞭解某些功能的能力。任何幫助,將非常感謝!
我得到一個錯誤,當我嘗試運行代碼: 線[12點14分] =「{:02} '.format(p-12) TypeError:'str'對象不支持項目分配 – br459jr
@ ueser2525679:對不起,已編輯。 – dugres
我覺得我們很接近...當我運行這個代碼時,它仍然輸出: '週二25 ** 15 ** 336 0 0 0 0 0 週二25 ** 04 ** 12682 0 0 0 0 0 星期二Jun 25 ** 05 ** 12636 0 0 0 0 0 星期二25 ** 06 ** 12450 0 0 0 0 0 星期二25 ** 07 ** 12640 0 0 0 0 0' and我在變量t上做了一個打印,它具有正確的值,看起來好像不會將該值寫入文檔。幾乎像「行」沒有得到值「t」更新。 – br459jr