Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/list/file/loop/append

I have to open a file and loop through the list. Then I have to print the results and append/write certain lines to the same file. I want to be able to run the code multiple times, but I do not want to append certain lines multiple times and I do not want to read appended lines. The question is - how to append/write only once and how to skip reading appended lines? Here is the code:

kitty = 500

requests = []

file = open("loan_requests.txt", "r+")

requests = file.readlines()


for item in requests:

    flag = bool(int(item))
    if flag == False:
        break

    
    if  int(item) <= kitty and kitty > 0:
            kitty = kitty - int(item)
            loan = int(item)
            print(loan, "- Paid!")
            file.write("Request of {} paid in full.\n".format(loan))
        
    elif int(item) > kitty and kitty > 0:
             kitty = kitty - int(item)
             loan = int(item) + kitty
             print(int(item), "Request cannot be processed in full (Insufficient funds available). Amount paid:", loan)
             file.write("Request of {} could not be paid in full.Partial payment of {} made.\n".format(item, loan))

    elif int(item) > kitty and kitty <= 0:
             print("Request of", int(item), "is UNPAID!")
             file.write("Outstanding Request:{}\n".format(item))


file.close()



Tried with seek(); tell(). 
like image 353
Dinko Spahija Avatar asked Jul 01 '26 02:07

Dinko Spahija


1 Answers

Before writing to the file, check if the file already contains that line.

kitty = 500

requests = []

file = open("loan_requests.txt", "r+")

requests = file.readlines()

def write_new(file, line, requests):
    if line not in requests:
        file.write(line)

for item in requests:
    
    if int(item) < kitty and kitty > 0:
        kitty = kitty - int(item)
        loan = int(item)
        write_new(file, "Request of {} paid in full.\n".format(loan), requests)
        print(loan, "- Paid!")

    elif int(item) > kitty and kitty > 0:
        kitty = kitty - int(item)
        loan = int(item) + kitty
        write_new(file, "Request of {} could not be paid in full.Partial payment of {} made.\n".format(item, loan), requests)
        print(int(item), "request cannot be processed in full (Insufficient funds available). Amount paid:", loan)
            
    elif int(item) > kitty and kitty <= 0:
        write_new(file, "Outstanding Request:{}\n".format(item), requests)
        print("Request of", int(item), "is UNPAID!")

file.close()
like image 116
Barmar Avatar answered Jul 03 '26 14:07

Barmar