Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import csv
- import os
- def update_csv_keys(file_path):
- try:
- # Extract the filename without extension for key generation
- filename = os.path.splitext(os.path.basename(file_path))[0]
- with open(file_path, mode='r', newline='') as file:
- # Reading the CSV file
- reader = csv.DictReader(file)
- rows = list(reader)
- # Clear existing content in the "Key" column
- for row in rows:
- row['Key'] = ''
- # Index for key generation
- key_index = 1
- added_keys = []
- # Update rows
- for row in rows:
- if row['Line']: # Check if 'Line' column is not empty
- new_key = f'{filename}_{key_index}'
- row['Key'] = new_key
- added_keys.append(new_key)
- key_index += 1
- with open(file_path, mode='w', newline='') as file:
- # Writing back to the CSV file
- fieldnames = reader.fieldnames
- writer = csv.DictWriter(file, fieldnames=fieldnames)
- writer.writeheader()
- writer.writerows(rows)
- return added_keys
- except Exception as e:
- return f"An error occurred: {e}"
- # Ask for the CSV file path
- file_path = input("Enter the path to the CSV file: ")
- result = update_csv_keys(file_path)
- # Check if the result is an error message or keys
- if isinstance(result, list):
- # Print all added keys
- print("\nAdded keys:")
- for key in result:
- print(key)
- print("\nCSV file has been updated.")
- else:
- # Print the error message
- print(result)
Advertisement
Add Comment
Please, Sign In to add comment