2015-01-14 3 views
0

У меня есть текстовый файл, который содержит:разница между строками и заполнить столбцы

Week OrangeTotal ODifference AppleTotal ADifference 
1  2   -   3   - 
2  5   ?   4   ? 
3  10   ?   10   ? 
4  50   ?   100  ? 

Я хотел бы, чтобы пропустить первую строку, так как это начало нового года, но заполнить колонку рядом с ним с вычитанием этой строки и строки ниже.

Оно должно быть:

Week OrangeTotal ODifference AppleTotal ADifference 
1  2   -   3   - 
2  5   3   4   1 
3  10   5   10   6 
4  50   40   100  90 
+6

Это хорошо! Что вы пытались, где вы застряли? Где ваш код, чтобы мы могли помочь вам решить проблемы, с которыми вы столкнулись. –

+1

Также, пожалуйста, найдите время, чтобы просмотреть предыдущие вопросы и [принять некоторый ответ] (http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work), если он решил вашу проблему , – elyase

+0

Я могу использовать regex replace – PVNRT

ответ

1
import os 


def main(): 
    name = 'log.txt' 
    tmpName = 'tmp.txt' 
    f = open(name, 'r') 
    tmp = open(tmpName, 'w') 

    titleLine = f.readline().strip() 
    tmp.write(titleLine+'\n') 

    prevLine = f.readline().strip() 
    tmp.write(prevLine+'\n') 
    prevLine = prevLine.split('\t') 

    for line in f: 
     line = line.split('\t') 
     line[2] = str(int(line[1]) - int(prevLine[1])) 
     line[4] = str(int(line[3]) - int(prevLine[3])) 
     prevLine = line 

     displayLine='' 
     for i in range(len(line)-1): 
      displayLine += line[i]+'\t' 
     displayLine += line[len(line)-1] 

     tmp.write(displayLine+'\n') 

    f.close() 
    tmp.close() 
    os.remove(name) 
    os.rename(tmpName, name) 


main() 
+0

Это работает !!!!!!!!! Какой гений –

0
import os 

import sys 

ds = open("Path.txt",'r').readlines() 
a = list() 
b = list() 
for words in ds[1:]: 
    a.append(words) 
for words in ds: 
    b.append(words) 

for lines in a: 
    again = int(lines) 
    for words in b: 
     bse = int(words) 
     print bse-again 
+0

Пожалуйста, дайте объяснение re: как это решает исходный вопрос. – brandonscript

0

до сих пор я думаю, что может быть проще работать с каждой строки в цикле, как for lines in ds[1:]: цикла. также важно отметить, что readlines создает массив строк файла. Так ds[0] = 'Week OrangeTotal ODifference AppleTotal ADifference'

так что вам нужно цикл по линиям

old=0 # this is to store the last value 
done = list() 
for i in range(1, len(ds), 1):  #[range()][1] 
    l=0 # we define l here so that the garbage collector does not decide we no longer need it 
    if(old!=0):   #if this is not the first one 
     l = ds[i].split()  
         # [split()][2] gets rid of whitespace and turns it into a list 
     for v in range(1, 3, 2): 
       #we skip the first value as that is the week and then next as that is the answer 
      ds[v+1] = ds[v] - old[v] #here is where we do the actual subtraction and store the value 
    old = l #when we are done we set the row we finished as old 
    done[i] = l.join(" ") 
    print(str(done[i])) 

, что вы делаете с этим здесь ваше решение