Created
November 29, 2012 20:27
-
-
Save matthewbelisle-wf/4171684 to your computer and use it in GitHub Desktop.
Sample script to convert an xml file into a csv file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Where can I add some encoding parameters? Thanks anyway