0

I writing some unicode output to csv using the unicodecsv module. Everything is working as expected, but I'm trying to build it out by adding some headers or field names. So far, I've tried a number of different ways, but I can't come up with how to add the field names.

I've tried other unicode solutions and this module seems to be the most elegant to implement so I'm trying to use it if possible. If there are other suggestions, I'm up for them. Any ideas?? Please see relevant code below.

import unicodecsv

with open('c:\pull.csv', 'wb+') as f:
            csv_writer = unicodecsv.writer(f, encoding='utf-8')
            for i in changes['user']['login'], changes['title'], str(changes['changed_files']), str(changes['commits']) :
                csv_writer.writerow([changes['user']['login'], changes['title'],changes['changed_files'], changes['commits']])

Sample output for changes in the csv file:

'John Doe', 'Some Title', 1, 1

4
  • Can you edit the question to give a small example for changes. Also what headers do you want to add? Commented Sep 3, 2015 at 6:57
  • @MartinEvans I adjusted the example with sample output. I would like for the headers to be Name, Title, Changed Files, Commits. Thanks for any help you can provide. Commented Sep 3, 2015 at 18:39
  • 1
    Could you though add some sample input for what changes would containe? Commented Sep 3, 2015 at 18:40
  • @MartinEvans The output is the json returned by querying GitHub for getting a single pull request. Please see here: developer.github.com/v3/pulls/#get-a-single-pull-request. Commented Sep 3, 2015 at 18:55

1 Answer 1

1

For the json data you have, there is only one user entry, so the following should work:

with open('c:\pull.csv', 'wb+') as f:
    csv_writer = unicodecsv.writer(f, encoding='utf-8')

    # Write a header row (do once)
    # csv_writer.writerow(["login", "title", "changed_files", "commits"])

    # Write data row
    csv_writer.writerow([changes['user']['login'], changes['title'],changes['changed_files'], changes['commits']])

If you want a header row, uncomment the line. This would then give you an output file:

login,title,changed_files,commits
octocat,new-feature,5,3
Sign up to request clarification or add additional context in comments.

1 Comment

@MartinEvans...That worked like a charm (knocking myself in the head, because I should have thought to try that). Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.