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(" ").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' above is my code, the function is to get data(last line) from txt file and read it, get new data and write it to the txt file again by creating new line. my txt file(current balance.txt) should look like this: 2894.00 2694.00 but when i try to use the last line which is 2694.00 to do calculation(rf=a-rr), it failed returning this error: 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 else if i use this code: for line in open(tf): pass a = line rf=a-rr it return this error: 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' I seriously have no idea why...please help me...
To obtain last line of the file, you can simple do 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(' '))
The function input is giving you a string. Try doing: rf=a-float(rr)
How to create random orthonormal matrix in python numpy
Fill an image with pre-defined pattern with Wand
How to use a post_save receiver with django-polymorphic?
giving a name to a pandas dataframe?
mistake comparing datetime, python
numpy testing assert array NOT equal
How to join threads of an asyncio executor runned inside coroutine?
Google Admin SDK insert custom schema using python
Importing images for manifold Isomap
Having nosetests watch files from outside container and rerun tests inside container
Trying to ftp from my system to remote server
Attribute in a Class immediately runs at the wrong time?
Unable to handle “HTTP Badstatus line” exception
How to merge/join two resultset/table in django?
Maximise the Slope using CVXPY
Python-Instagram user_recent_media returning next of none