CaiusNelson

Python - Add "Key" to csv game script

Jan 15th, 2024
1,234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | Gaming | 0 0
  1. import csv
  2. import os
  3.  
  4. def update_csv_keys(file_path):
  5.     try:
  6.         # Extract the filename without extension for key generation
  7.         filename = os.path.splitext(os.path.basename(file_path))[0]
  8.  
  9.         with open(file_path, mode='r', newline='') as file:
  10.             # Reading the CSV file
  11.             reader = csv.DictReader(file)
  12.             rows = list(reader)
  13.  
  14.         # Clear existing content in the "Key" column
  15.         for row in rows:
  16.             row['Key'] = ''
  17.  
  18.         # Index for key generation
  19.         key_index = 1
  20.         added_keys = []
  21.  
  22.         # Update rows
  23.         for row in rows:
  24.             if row['Line']:  # Check if 'Line' column is not empty
  25.                 new_key = f'{filename}_{key_index}'
  26.                 row['Key'] = new_key
  27.                 added_keys.append(new_key)
  28.                 key_index += 1
  29.  
  30.         with open(file_path, mode='w', newline='') as file:
  31.             # Writing back to the CSV file
  32.             fieldnames = reader.fieldnames
  33.             writer = csv.DictWriter(file, fieldnames=fieldnames)
  34.             writer.writeheader()
  35.             writer.writerows(rows)
  36.  
  37.         return added_keys
  38.  
  39.     except Exception as e:
  40.         return f"An error occurred: {e}"
  41.  
  42. # Ask for the CSV file path
  43. file_path = input("Enter the path to the CSV file: ")
  44. result = update_csv_keys(file_path)
  45.  
  46. # Check if the result is an error message or keys
  47. if isinstance(result, list):
  48.     # Print all added keys
  49.     print("\nAdded keys:")
  50.     for key in result:
  51.         print(key)
  52.     print("\nCSV file has been updated.")
  53. else:
  54.     # Print the error message
  55.     print(result)
  56.  
Advertisement
Add Comment
Please, Sign In to add comment