行和填充列之间的差异

时间:2015-01-14 17:49:37

标签: python text python-2.5 subtraction

我有一个包含以下内容的文本文件:

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

3 个答案:

答案 0 :(得分: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()

答案 1 :(得分: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

答案 2 :(得分:0)

到目前为止,我认为您可能更容易使用for for lines in ds[1:]:循环等for循环中的每一行。同样重要的是要注意,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]))

你从这里做的是你的决定