I have the following source code, where I am trying to write a list in a csv file. I need every new list to be written in a new line of this csv file. The source code is the following:
import csv
list1=[55,100,'dir1/dir2/dir3/file.txt',0.8]
resultFile = open("output.csv",'wa')
wr = csv.writer(resultFile, dialect='excel')
wr.writerow(list1)
resultFile.close()
The problem is that it doesn't insert list1 in a newline every time i run the code.
In matlab that would be easy, I just need to use dlmwrite with '-append' parameter.
But how to do this in Python?
Open file in append mode.
import csv
list1=[58,100,'dir1/dir2/dir3/file.txt',0.8]
with open("output.csv", "a") as fp:
wr = csv.writer(fp, dialect='excel')
wr.writerow(list1)
More on file open modes
try following:-
>>> with open('test1','wb') as f: f.write('test')
...
>>> with open('test1','ab') as f: f.write('koko')
...
>>> with open('test1','rb') as f: f.read()
...
'testkoko'
>>> with open('test1','wa') as f: f.write('coco')
...
>>> with open('test1','rb') as f: f.read()
...
'coco'
>>>
From this link
Modes : Description
If you use Python 3.x then change your code:
import csv
list1 = [58,100,'dir1/dir2/dir3/file.txt',0.8]
with open("output.csv", "a", newline='') as fp:
wr = csv.writer(fp, dialect='excel')
wr.writerow(list1)
Adding newline=''
can help you to avoid getting extra new lines, empty rows in between two rows with data.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.