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 abale to run the code multiple times, but I do not want to append certain lines multiple times, but only once. The question is - how to append/write only once? Here is the code:
kitty = 500
requests = []
file = open("loan_requests.txt", "r ")
requests = file.readlines()
for item in requests:
if int(item) < kitty and kitty > 0:
kitty = kitty - int(item)
loan = int(item)
file.write("Request of {} paid in full.".format(loan))
print(loan, "- Paid!")
elif int(item) > kitty and kitty > 0:
kitty = kitty - int(item)
loan = int(item) kitty
file.write("Request of {} could not be paid in full.Partial payment of {} made.".format(item, loan))
print(int(item), "request cannot be processed in full (Insufficient funds available). Amount paid:", loan)
elif int(item) > kitty and kitty <= 0:
file.write("Outstanding Request:{}".format(item))
print("Request of", int(item), "is UNPAID!")
file.close()
I tried to use break method, but it doesn't help.
CodePudding user response:
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()
CodePudding user response:
Converting what Barman suggests, let's start with helper function that will write or not depends on some flag:
SHOULD_WRITE = True
def maybe_write(file, message):
if SHOULD_WRITE:
file.write(message)
Now use that function instead of file.write
:
# file.write("Request of {} paid in full.".format(loan))
maybe_write(file, f"Request of {loan} paid in full.")
Next time, change value of SHOULD_WRITE = False
BONUS: Do you know python has such fancy syntax?
if 0 < kitty < int(item):
...