PsychoStatic

Notepad to Json

May 22nd, 2023
3,579
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. import os
  2. import json
  3.  
  4. def export_to_json_from_files():
  5.     directory = os.getcwd()
  6.     json_data = {}
  7.  
  8.     # Check if the JSON file already exists
  9.     if os.path.isfile("album_data.json"):
  10.         with open("album_data.json", "r") as json_file:
  11.             json_data = json.load(json_file)
  12.  
  13.     # Get the highest index in the existing JSON data
  14.     highest_index = max(map(int, json_data.keys())) if json_data else 0
  15.  
  16.     for filename in os.listdir(directory):
  17.         if filename.endswith(".txt"):
  18.             filepath = os.path.join(directory, filename)
  19.             with open(filepath, "r") as file:
  20.                 lines = file.readlines()
  21.                 scores = []
  22.                 for line in lines:
  23.                     track_info = line.split(":")
  24.                     if len(track_info) >= 2:
  25.                         score = track_info[1].strip()
  26.                         if score == "NR":
  27.                             scores.append("NR")
  28.                         else:
  29.                             try:
  30.                                 scores.append(float(score))
  31.                             except ValueError:
  32.                                 scores.append("Invalid Score")
  33.                     else:
  34.                         scores.append("Missing Score")
  35.  
  36.                 average_score = float(lines[-1].split(":")[1].strip())
  37.  
  38.                 artist, album = os.path.splitext(filename)[0].split(" - ")
  39.                 data = {
  40.                     "Artist_Title": artist,
  41.                     "Album_Title": album,
  42.                     "Scores": scores,
  43.                     "Average_Score": average_score
  44.                 }
  45.  
  46.                 # Assign the next available index
  47.                 highest_index += 1
  48.                 json_data[str(highest_index)] = data
  49.  
  50.     with open("album_data.json", "w") as json_file:
  51.         json.dump(json_data, json_file, indent=4)
  52.  
  53. export_to_json_from_files()
  54.  
Advertisement
Add Comment
Please, Sign In to add comment