[Tutor] exporting lists into CSV issue.
Alan Gauld
alan.gauld at yahoo.co.uk
Tue Jan 22 05:22:30 EST 2019
On 22/01/2019 09:25, mhysnm1964 at gmail.com wrote:
> being exported to the CSV. But when I bring it into Excel. I am getting a
> blank row between each row. The exported data looks like this:
I can't see anything obvious.
> import plistlib, pprint, csv
>
> with open("library.xml", "rb") as f:
> data = plistlib.load(f)
>
> books =[['Name', 'Artist', 'Kind', 'Total Time', 'Year', 'Date Modified',
> 'Date Added', 'Bit Rate', 'Sample Rate', 'Comments', 'Location']]
>
> for book in list(data['Tracks'].values()):
You don't need to convert to list.
You can just iterate over the values().
I don't think that should add any newlines but it
might be worth removing the list to see.
>
> tmp = []
> if not 'Audible file' in book['Kind']:
> break # skip book
> for key in books[0]:
> if key in book:
> tmp.append(book[key])
> else:
> tmp.append("")
> books.append(tmp
>
> with open ('books-list.csv', 'w') as wf:
> writer = csv.writer(wf)
> writer.writerows(books)
You could try writing(and printing) the rows individually:
for row in books:
# print(row) # debugging only
writer.writerow(row)
To see if it is writerows() that is adding the spurious lines.
If that's the case there may be a parameter to change
or suppress the separator.
It might also be easier to use the csv.dictwriter
since your data appears to be in the form of a dict
to start with. Although I'm not sure how dictwriter
copes with missing fields.
> wf.close()
Don't use close() if you are using "with open..."
Closing is done automatically. It's one of the
advantages of the 'with' style.
hth
--
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list