行和填充列之间的差异

Difference Between Rows and fill Columns

我有一个文本文件,其中包含:

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

到目前为止,我认为您可以更轻松地处理 for 循环中的每一行,例如 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]))

你从这里用它做什么是你的决定

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()