Export results of print in csv file

Hi every one!
I have result lot of rows but in csv file just one row. Why just one row in file ?
It’s just example of list files in folder and subfolders. Could you please help me ?

import os
import csv
directory = r"c:\Temp\20_MDG_Congo_MarineXII"
for root, dirs, files in os.walk(directory):
for file in files:
result = (file,os.path.join(root,file),os.stat(os.path.join(root,file)).st_size)
print (result)
with open(‘C:/Temp/20_MDG_Congo_MarineXII/opa2.csv’, ‘w’) as f:
write = csv.writer(f)
write.writerow(result)

Enclose the code in “```” to preserve indentation.

Note that in every iteration you open the file opa2.csv, in mode w, write in it, and then close it.
This means that every time, it gets overwritten.

Either open the file in mode a, to append, instead, or open it once in mode w, but do the loop(s) and work that computes each result inside the scope of the with open ... .

1 Like

As @franklinvp suggests, moving the file open before your loops will solve the issue:

import os
import csv
directory = r"c:\Temp\20_MDG_Congo_MarineXII"
write = csv.writer(f)
with open('C:/Temp/20_MDG_Congo_MarineXII/opa2.csv', 'w') as f:
    for root, dirs, files in os.walk(directory):
        for file in files:
        result = (file,os.path.join(root,file),os.stat(os.path.join(root,file)).st_size)
        print (result)
        write.writerow(result)

Thank you so much.
Yours suggests are working