import csv
import os
# --- Configuration ---
input_filename = 'harfancoffee_products.csv' # Replace with your input file name
output_filename = 'harfancoffee_products.csv' # Name for the output file
# Or set output_filename = input_filename to overwrite the original file (use with caution!)
new_column_name = 'store_name' # Name of the new column
new_column_value = 'harfancoffe' # The value to put in the new column for every row
# --- Processing ---
# Use a temporary file if overwriting the original
temp_filename = output_filename + '.temp' if output_filename == input_filename else output_filename
try:
# Open the input file for reading and the temporary/output file for writing
# Use newline='' to prevent extra blank rows in CSV output
# Use encoding='utf-8' for broader compatibility
with open(input_filename, 'r', newline='', encoding='utf-8') as infile, \
open(temp_filename, 'w', newline='', encoding='utf-8') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
# Read and process the header row
try:
header = next(reader) # Get the first row (header)
new_header = header + [new_column_name] # Add the new column name
writer.writerow(new_header) # Write the new header to the output file
except StopIteration:
# Handle case where the input file is empty (or just has a header, which next() consumed)
# Write only the new header to the output file
writer.writerow([new_column_name])
header = None # Indicate no original header or data rows were processed
# Process the data rows (if any)
if header is not None or os.stat(input_filename).st_size > 0: # Process if original file had content
for row in reader:
# Append the new value to the end of each row
row.append(new_column_value)
writer.writerow(row) # Write the modified row to the output file
# If we were overwriting, replace the original file with the temporary one
if output_filename == input_filename:
os.replace(temp_filename, input_filename)
print(f"Successfully added column '{new_column_name}' with value '{new_column_value}' to {input_filename} (original file overwritten).")
else:
print(f"Successfully added column '{new_column_name}' with value '{new_column_value}' to {input_filename} and saved to {output_filename}.")
except FileNotFoundError:
print(f"Error: Input file '{input_filename}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Clean up the temporary file if an error occurred during processing
if output_filename == input_filename and os.path.exists(temp_filename):
os.remove(temp_filename)
print(f"Cleaned up temporary file '{temp_filename}'.")