2013-06-26 58 views
0

我真的很新的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() 

的主要問題是它不是通過每個迭代線或進行更新。甚至可能有更好的方法來做我想做的事情,只是沒有知識或者不瞭解某些功能的能力。任何幫助,將非常感謝!

回答

0
inp = open("filelocation").readlines() 
with open("filelocation", "w") as out: 
    for line in inp: 
     t = line[12:14] 
     p = int(t) 
     if p>12: 
      line = '{}{:02}{}'.format(line[:12], p-12, line[14:]) 
     out.write(line) 
+0

我得到一個錯誤,當我嘗試運行代碼: 線[12點14分] =「{:02} '.format(p-12) TypeError:'str'對象不支持項目分配 – br459jr

+0

@ ueser2525679:對不起,已編輯。 – dugres

+0

我覺得我們很接近...當我運行這個代碼時,它仍然輸出: '週二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

1
for line in infile: 
    print line, infile 
    line = fun(line, infile.next()) 
    break 

break離開電流回路,所以這將只在第一行運行,然後停止。

爲什麼你的fun函數在文件上運行而不是線?你已經有了這條線,所以沒有理由再讀一遍,而且我認爲把它寫回來是一個壞主意。儘量使其具有這種功能的簽名工作:

def fun(line): 
    # do things 
    return changed_line 

爲了處理文件,你可以使用with statement使這個更簡單,更防呆:

with open("filelocation", "a+") as infile: 
    for line in infile: 
     line = fun(line) 
# infile is closed here 

對於輸出,這是相當困難的寫回你從讀取相同的文件,所以我建議剛打開一個新的輸出文件:

with open(input_filename, "r") as input_file: 
    with open(output_filename, "w") as output_file: 
     for line in input_file: 
      output_file.write(fun(line)) 

或者你可以閱讀了整個事情的,然後寫這一切回來了(但根據文件的大小,這可能會使用大量內存):

output = "" 
with open(filename, "r") as input_file: 
    for line in input_file: 
     output += fun(line) 
with open(filename, "w") as output_file: 
    output_file.write(output) 
相關問題