读取python中txt文件的最后一行并将其更改为变量进行计算

2024-05-17 06:22:32 发布

您现在位置:Python中文网/ 问答频道 /正文

td = 'date of transaction.txt'
tf = 'current balance.txt'
tr = 'transaction record.txt'
for line in open(tf):pass
for line2 in open(td):pass
for line3 in open(tr):pass
print line2,line,line3
"""
so call recall back last record
"""
rd=raw_input('\ndate of transaction: ')
print "Choose a type of transaction to proceed... \n\tA.Withdrawal \n\tB.Deposit \n\tC.Cancel & exit"
slc=raw_input('type of transaction: ')
i=1
while (i>0):
    if slc=="A" or slc=="B" or slc=="C":
    i=0
else:
    i=i+1
    slc=raw_input('invalid selection, please choose again...(A/B/C): ')
if slc=="A":
    rr=input('\namount of transaction: ')
    Line_len = 10 # or however long a line is, since in my example they all looked the same
    SEEK_END = 2
    file = open(tf, "r")
    file.seek(-Line_len, SEEK_END)
    a = int(str(file.read(Line_len)).split(" ")[0].strip())
    rf=a-rr
    f1=open(tf, 'a+')
    f1.write('\n'+rf)
    f1.close()
    d1=open(td, 'a+')
    d1.write('\n'+rd)
    d1.close
    r1=open(tr, 'a+')
    r1.write('\n-'+rr)
    r1.close
else:
    print 'later'

上面是我的代码,功能是从txt文件中获取数据(最后一行)并读取它,获取新数据并通过创建新行将其再次写入txt文件。 我的txt文件(current balance.txt)应该如下所示:

2894.00
2694.00

但是,当我试图使用最后一行2694.00进行计算(rf=a-rr)时,它未能返回以下错误:

Traceback (most recent call last):
  File "C:\Python27\acc.py", line 27, in <module>
    file.seek(-Line_len, SEEK_END)
IOError: [Errno 22] Invalid argument

否则,如果我使用此代码:

for line in open(tf):
    pass
a = line
rf=a-rr

它返回此错误:

Traceback (most recent call last):
  File "C:\Python27\acc.py", line 27, in <module>
    rf=a-rr
TypeError: unsupported operand type(s) for -: 'str' and 'int'

我真的不知道为什么…请帮帮我。。。


Tags: ofintxtforinputlentfline