How do append/write only once a file in python?

2 min read In Question/Ans

Question

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, but only once. The question is – how to append/write only once? Here is the code:

#include <algorithm>
#include <ctime>
#include <iostream>

int main()
{
    // Generate data
    const unsigned arraySize = 32768;
    int data[arraySize];

    for (unsigned c = 0; c < arraySize; ++c)
        data[c] = std::rand() % 256;

    // !!! With this, the next loop runs faster.
    std::sort(data, data + arraySize);

    // Test
    clock_t start = clock();
    long long sum = 0;
    for (unsigned i = 0; i < 100000; ++i)
    {
        for (unsigned c = 0; c < arraySize; ++c)
        {   // Primary loop.
            if (data[c] >= 128)
                sum += data[c];
        }
    }

    double elapsedTime = static_cast<double>(clock()-start) / CLOCKS_PER_SEC;

    std::cout << elapsedTime << '\n';
    std::cout << "sum = " << sum << '\n';
}

I tried to use the break method, but it doesn’t help.

Answer

To append/write only once to the file, you can use a boolean flag variable to track whether a certain line has been written to the file or not.

Here’s an example of how you can modify your code to achieve this:

kitty = 500

requests = []

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

requests = file.readlines()

# Initialize a flag variable to track whether the "Outstanding Request" line has been written
request_unpaid = False

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 and not request_unpaid:
        # Write the "Outstanding Request" line only if it has not been written before
        file.write("Outstanding Request:{}".format(item))
        request_unpaid = True
        print("Request of", int(item), "is UNPAID!")

file.close()

With this modification, the “Outstanding Request” line will be written to the file only once, even if multiple requests are unpaid.

Written by

Asheesh Gupta

Leave a Reply

Your email address will not be published. Required fields are marked *