How to write to a CSV line by line?
General way:
##text=List of strings to be written to filewith open('csvfile.csv','wb') as file: for line in text: file.write(line) file.write('\n')
OR
Using CSV writer :
import csvwith open(<path to output_csv>, "wb") as csv_file: writer = csv.writer(csv_file, delimiter=',') for line in data: writer.writerow(line)
OR
Simplest way:
f = open('csvfile.csv','w')f.write('hi there\n') #Give your csv text here.## Python will convert \n to os.linesepf.close()
You could just write to the file as you would write any normal file.
with open('csvfile.csv','wb') as file: for l in text: file.write(l) file.write('\n')
If just in case, it is a list of lists, you could directly use built-in csv
module
import csvwith open("csvfile.csv", "wb") as file: writer = csv.writer(file) writer.writerows(text)
I would simply write each line to a file, since it's already in a CSV format:
write_file = "output.csv"with open(write_file, "wt", encoding="utf-8") as output: for line in text: output.write(line + '\n')
I can't recall how to write lines with line-breaks at the moment, though :p
Also, you might like to take a look at this answer about write()
, writelines()
, and '\n'
.