Advertisement
Python253

json2csv

Mar 14th, 2024
529
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: json2csv.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script converts a JSON file (.json) to a CSV file (.csv).
  10. It reads the JSON file and writes the specified 'text_content' to the CSV file.
  11.  
  12. Requirements:
  13. - Python 3.x
  14.  
  15. Usage:
  16. 1. Save this script as 'json2csv.py'.
  17. 2. Ensure your JSON file ('example.json') is in the same directory as the script.
  18. 3. Run the script.
  19. 4. The converted CSV file ('json2csv.csv') will be generated in the same directory.
  20.  
  21. Note: Adjust the 'json_filename' and 'csv_filename' variables in the script as needed.
  22. """
  23.  
  24. import csv
  25. import json
  26.  
  27. def json_to_csv(json_filename, csv_filename):
  28.     with open(json_filename, 'r') as jsonfile, open(csv_filename, 'w', newline='') as csvfile:
  29.         data = json.load(jsonfile)
  30.         if "text_content" in data:
  31.             csvwriter = csv.writer(csvfile)
  32.             csvwriter.writerow([data["text_content"]])
  33.  
  34. if __name__ == "__main__":
  35.     json_filename = 'example.json'
  36.     csv_filename = 'json2csv.csv'
  37.     json_to_csv(json_filename, csv_filename)
  38.     print(f"Converted '{json_filename}' to '{csv_filename}'.")
  39.  
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement