Skip to content

Instantly share code, notes, and snippets.

@matthewbelisle-wf
Created November 29, 2012 20:27
Show Gist options
  • Save matthewbelisle-wf/4171684 to your computer and use it in GitHub Desktop.
Save matthewbelisle-wf/4171684 to your computer and use it in GitHub Desktop.
Sample script to convert an xml file into a csv file
#!/usr/bin/env python3
"""
Sample script to convert an xml file into a csv file.
Dependencies:
http://pypi.python.org/pypi/beautifulsoup4
http://pypi.python.org/pypi/lxml
"""
import csv
import os
from bs4 import BeautifulSoup
_this_dir = os.path.dirname(os.path.abspath(__file__))
# Parses the xml file
with open(os.path.join(_this_dir, 'sample.xml')) as fhandle:
soup = BeautifulSoup(fhandle.read(), 'xml')
if __name__ == '__main__':
# Opens a csv file
with open(os.path.join(_this_dir, 'sample.csv'), 'w') as fhandle:
writer = csv.writer(fhandle)
writer.writerow(('Title', 'Author', 'Genre'))
for song in soup.find_all('song'):
writer.writerow((song.title.text,
song.author.text,
song.genre.text))
<?xml version="1.0"?>
<list>
<song>
<title>Song 1</title>
<author>Author 1</author>
<genre>Genre 1</genre>
</song>
<song>
<title>Song 2</title>
<author>Author 2</author>
<genre>Genre 2</genre>
</song>
<song>
<title>Song 3</title>
<author>Author 3</author>
<genre>Genre 3</genre>
</song>
</list>
@koalaGreener
Copy link

Where can I add some encoding parameters? Thanks anyway

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment