簡體   English   中英

在python中讀取txt文件的最后一行並將其更改為變量以進行計算

[英]reading last line of txt file in python and change it into variable to make calculation

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文件(當前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'

我真的不知道為什么...請幫助我...

要獲取文件的最后一行,您可以簡單地執行

with open('my_file.txt') as file:
     last_line = file.readlines()[-1]

#last_line is a string value pointing to last line, to convert it into float, you can do

number = float(last_line.strip('\n').strip(' '))

函數輸入為您提供了一個字符串。 嘗試做:

rf=a-float(rr)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM