0

Im having troubles saving the output into a specific file path like a csv file output just that my codes are simpler and it have 'with open(xxx)'.

So here are my codes. How do i print 'out' into a specific file path e.g /home/pi/Desktop/sample.json?

    import csv
    import json

    with open(csvfile, "a") as output:
       fieldnames = ['Name', 'Number', 'ID', 'Address']
       writer = csv.writer(output,delimiter = ',', lineterminator="\n")
       writer.writerows([fieldnames])
meh
  • 53
  • 1
  • 7
  • Check this link.. https://stackoverflow.com/a/12309296/4851248 – Ram Lakhan May 29 '17 at 07:43
  • Possible duplicate of [How do I write JSON data to a file in Python?](https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file-in-python) – Darkstarone May 29 '17 at 07:54
  • @RamLakhan hi! thanks for replying!! I've tried it but i realised that data = (hardcoded content) but i am using a variable. – meh May 29 '17 at 07:57
  • @Darkstarone hi!! thanks for the reply :) yes ive tried that too, its similar to the one in the website Ram gave – meh May 29 '17 at 07:59

1 Answers1

1

The easiest option is to leave you Python code as it is and use the power of the shell!

Assuming the script is in you current working directory, try this:

python myscript.py > sample.json

This will redirect the output (stdout) of your script to a file automatically creating it.

Kirill Rogovoy
  • 583
  • 3
  • 11