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)
Filtering models using date range
multiprocessing queue full
Python: How to run nested parallel process in python?
python-requests: Limit Number of Redirects Followed
Python/Bokeh - Plotting Data with Gaps on a Log Scale
Python Getting Level Settings
Variable Explorer freezes when viewing tuples in python Spyder IDE
Is there a way to automate the presentation of pandas Dataframes in an attractive manner
Move Y axis to another position in matplotlib
How to create multiple copies of rows by multiplication in pandas?
Looping to create Python arrays
Get the quotient when dividing a float in Python 2.7
Net Use in Python 3
Setting up postgresql in Travis CI for django project
How to get the current behave step with Python?
Assigning to python pandas column in a for loop NaN error on first iterant only