Advertisement
Python253

txt2json

Mar 15th, 2024
591
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: txt2json.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script converts a text file (.txt) to a JSON file (.json).
  10. Assumes the entire content of the text file is a single JSON string.
  11.  
  12. Requirements:
  13. - Python 3.x
  14.  
  15. Usage:
  16. 1. Save this script as 'txt2json.py'.
  17. 2. Ensure your text file ('example.txt') is in the same directory as the script.
  18. 3. Run the script.
  19. 4. The converted JSON file ('txt2json.json') will be generated in the same directory.
  20.  
  21. Note: Adjust the 'txt_filename' and 'json_filename' variables in the script as needed.
  22. """
  23.  
  24. import json
  25.  
  26. def txt_to_json(txt_filename, json_filename):
  27.     with open(txt_filename, 'r') as txtfile, open(json_filename, 'w') as jsonfile:
  28.         # Assuming the entire content of the text file is a single JSON string
  29.         data = {"text_content": "".join(txtfile)}
  30.         json.dump(data, jsonfile, indent=2)
  31.  
  32. if __name__ == "__main__":
  33.     # Set the filenames for the text and JSON files
  34.     txt_filename = 'example.txt'
  35.     json_filename = 'txt2json.json'
  36.  
  37.     # Convert the text to a JSON file
  38.     txt_to_json(txt_filename, json_filename)
  39.  
  40.     print(f"Converted '{txt_filename}' to '{json_filename}'.")
  41.  
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement