Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Write To File Missing Lines

I'm having trouble using python to write strings into a file: (what I'm trying to do is using python to generate some C programs) The code I have is the following:

filename = "test.txt"
i = 0
string = "image"
tempstr = ""
average1 = "average"
average2 = "average*average"
output = ""
FILE = open(filename,"w")
while i < 20:
    j = 0
    output = "square_sum = square_sum + "
    while j < 20:        
        tempstr = string + "_" + str(i) + "_" + str(j)        
        output = output + tempstr + "*" + tempstr + " + " + average2 + " - 2*" + average1 + "*" + tempstr        
        if j != 19:        
            output = output + " + "
        if j == 19:
            output = output + ";"        
        j = j + 1
    output = output + "\n"
    i = i + 1
    print(output)
    FILE.writelines(output)    
FILE.close

The print gives me correct output, but the FILE has last line missing and some of the second last line missing. What's the problem in writing strings into file?

Thank you!

like image 412
Ken Ma Avatar asked Dec 06 '25 19:12

Ken Ma


2 Answers

Probably help if you called the method...

FILE.close()
like image 140
Ignacio Vazquez-Abrams Avatar answered Dec 08 '25 16:12

Ignacio Vazquez-Abrams


The problem is that you aren't calling the close() method, just mentioning it in the last line. You need parens to invoke a function.

Python's with statement can make that unnecessary though:

with open(filename,"w") as the_file:
    while i < 20:
        j = 0
        output = "square_sum = square_sum + "
        ...
        print(output)
        the_file.writelines(output)

When the with clause is exited, the_file will be closed automatically.

like image 41
Ned Batchelder Avatar answered Dec 08 '25 17:12

Ned Batchelder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!