To address your requirement, we can implement a Python script that reads CSV files from an input directory, replaces {PARAM}-style tokens with actual values from a config.json file, and writes the modified content back to an output directory without renaming the files.
Here's a well-structured and commented implementation that ensures robustness and clarity:
✅ Python Script: replace_params_in_csv.py
import os
import json
def main():
# Configuration
config_path = 'config.json'
input_dir = 'input'
output_dir = 'output'
# Step 1: Load the configuration from config.json
try:
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
except FileNotFoundError:
print(f"Error: '{config_path}' not found.")
return
except json.JSONDecodeError as e:
print(f"Error decoding JSON in '{config_path}': {e}")
return
# Step 2: Ensure the output directory exists
os.makedirs(output_dir, exist_ok=True)
# Step 3: Process each CSV file in the input directory
for filename in os.listdir(input_dir):
if filename.endswith('.csv'):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
try:
# Read the CSV content
with open(input_path, 'r', encoding='utf-8') as f:
content = f.read()
# Replace all {PARAM} tokens with their corresponding values
for param_key, param_value in config.items():
content = content.replace(param_key, param_value)
# Write the modified content to the output directory
with open(output_path, 'w', encoding='utf-8') as f:
f.write(content)
print(f"Processed: {filename}")
except Exception as e:
print(f"Error processing {filename}: {e}")
if __name__ == '__main__':
main()
📁 Directory Structure
Ensure your project directory looks like this:
project-root/
│
├── input/
│ └── data.csv
│
├── output/
│
└── config.json
📄 Example config.json
{
"{PARAM_NO_1}": "value1",
"{ANOTHER_PARAM}": "value2"
}
📝 Example input/data.csv
Hello {PARAM_NO_1}, welcome {ANOTHER_PARAM}.
📤 Expected Output in output/data.csv
Hello value1, welcome value2.
⚠️ Notes & Considerations
- Encoding: This script uses UTF-8 encoding by default. You can adjust it if your files use a different encoding.
- Error Handling: The script includes basic error handling for missing files and JSON parsing issues.
- Token Matching: The replacement is case-sensitive and exact. Ensure your tokens in the CSV match the keys in
config.json.
This solution is efficient, clean, and suitable for typical use cases involving token replacement in CSV files. Let me know if you'd like to extend it to support more advanced features like nested replacements or templating engines (e.g., Jinja2).