Python how to write csv file

If you want to create csv file using python you can do:

csv = open("/home/user/my.csv", 'a')

for i in range(0, 20):
    element = str(i) + ";"
    written = csv.write(element)
csv.close()    

result:

0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;
0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;

the above example write to file in append mode - because of the parameter - 'a'

If you want first to truncate the file and then to write then you need to use - 'w':

csv = open("/home/user/my.csv", 'a')

for i in range(0, 20):
    element = str(i) + ";"
    written = csv.write(element)
csv.close()

result:

0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;

You may be interested in reading csv file with python: Python how to read csv file

Related Article