Skip to content Skip to sidebar Skip to footer

Python For Loop Save Only Last Value To Csv?

Used below lines of code for contour detection and its corresponding area calculation during printing the area all values are printed but while saving only last value got saved in

Solution 1:

In every iteration of the loop, you create a new, empty DataFrame, put one thing into it, and write it out to a file. Each time, it writes over the previous output and what is left at the end is the last one. This happens because the file is opened in write mode by default.

(If "write mode" means nothing to you, you should review Python file open modes in your favorite language reference.)

Fortunately, the to_csv function has a mode parameter that you can set to 'a' to open the file for appending. If you do that, each write should append to the end of the file.

Alternately, you could accumulate all the output in one big DataFrame and write the whole thing out once after the loop terminates. This would probably be faster, but would require more memory.

Post a Comment for "Python For Loop Save Only Last Value To Csv?"