Dateien verarbeiten und vorbereiten

Dateien umbenennen und verschieben

Nachdem ich die Daten gesammelt habe, muss ich sie umbenennen und verschieben, um sie für die Analyse und Modellierung vorzubereiten. Die Umbenennung und Verschiebung der Dateien umfasst das Anpassen der Dateinamen und das Verschieben der Dateien in den richtigen Ordner.

Aus der Datei ‚1743694.json‘ in dem Ordner ‚GER-Bundesliga_2324‘ wird die Datei 3_232430_1743694.json. Jeder Wettbewerb hat eine eigene ID, die ich vorher bei whoscored ausgelesen habe. Ich habe danach jedem Wettbewerb in Kombination mit der Saison eine eigene Season_ID vergeben, die den nächsten Suffix bildet. So kann ich hinterher nur am Dateinamen erkennen, um welchen Wettbewerb und welche Saison es sich handelt.

Die Daten werden verschoben, damit ich die Rohdaten von den bereinigten Daten trennen kann. Eventuell möchte ich die Rohdaten noch für andere Projekte verwenden. Um den Prozess zu beschleunigen, werden bereits verarbeitete Spiele übersprungen.

Code Beispiel

Die Funktion dazu:

def copy_and_rename_json_files(main_folder: str, competitions_df: pd.DataFrame) -> None:
    """
    Copy JSON files from subfolders, rename them based on competition data, and save them to a 'data' folder.

    Args:
        main_folder (str): The main directory containing subfolders with JSON files.
        competitions_df (pd.DataFrame): DataFrame containing competition information.

    Returns:
        None
    """
    # Create a subfolder 'data' inside the main folder
    test_folder = os.path.join(main_folder, 'data')
    os.makedirs(test_folder, exist_ok=True)

    for root, dirs, files in os.walk(main_folder):
        # Skip the 'data' folder
        if root == test_folder:
            print(f"Skipping 'data' folder: {root}")
            continue

        total_files = 0
        copied_files = 0

        for file in files:
            if file.endswith('.json'):
                total_files += 1
                source_path = os.path.join(root, file)

                # Check if the JSON file content is "null"
                try:
                    with open(source_path, 'r') as f:
                        content = json.load(f)
                        if content is None:
                            print(f"Skipping file with 'null' content: {source_path}")
                            continue
                except json.JSONDecodeError:
                    print(f"Invalid JSON in file: {source_path}")
                    continue
                except Exception as e:
                    print(f"Error reading file {source_path}: {e}")
                    continue

                # Extract match information from folder and file names
                folder_name_parts = root.split(os.path.sep)[-1].replace('-', '_').split('_')
                match_id = os.path.splitext(file)[0]

                if len(folder_name_parts) == 3:
                    short_name, competition_name, season_name_short = folder_name_parts
                    match_info = competitions_df[
                        (competitions_df['short_name'] == short_name) &
                        (competitions_df['competition_name'] == competition_name) &
                        (competitions_df['season_name_short'] == int(season_name_short))
                        ]

                    if not match_info.empty:
                        competition_id = match_info['competition_id'].values[0]
                        season_id = match_info['season_id'].values[0]

                        new_filename = f"{competition_id}-{season_id}-{match_id}.json"
                        destination_path = os.path.join(test_folder, new_filename)

                        # Check if the file already exists in the destination folder
                        if not os.path.exists(destination_path):
                            shutil.copyfile(source_path, destination_path)
                            copied_files += 1
                            print(f"Copied and renamed file: {source_path} -> {destination_path}")
                        else:
                            print(f"File already exists: {destination_path}")

        # Display folder statistics
        print(f"Folder processed: {root}")
        print(f"Total files: {total_files}, Copied files: {copied_files}")