I'm creating a Lambda function with python for STAGE and PROD environment which will generate a random CSV files. But I need to have a dynamic filename.
I have the current code as below:
filename = "/tmp/userdata_%d%d%d-%d-%d-%d.csv" % (ts.tm_year, ts.tm_mon, ts.tm_mon, ts.tm_hour, ts.tm_min, ts.tm_sec)
I have configured ENVIRONMENT VARIABLES within the lambda function (like ENV = prod)
Expected Behavior:
- Stage filename - staging_userdata_202211-20-4-53.csv
- Prod filename - production_userdata_202211-23-3-35.csv
I tried something like below, but ended up with errors as I'm very new to Python.
file_prefix = "/tmp/"
file_suffix = "userdata_%d%d%d-%d-%d-%d.csv" % (ts.tm_year, ts.tm_mon, ts.tm_mon, ts.tm_hour, ts.tm_min, ts.tm_sec)
filename = (os.path.join(file_prefix, os.getenv('ENV'), file_suffix))
Got the below error:
{
"errorMessage": "[Errno 2] No such file or directory: '/tmp/staging/userdata_202211-21-27-36.csv'",
"errorType": "FileNotFoundError",
"stackTrace": [
" File \"/var/task/generate_csv.py\", line 26, in handler\n with open(filename, 'w', newline='') as csvfile:\n"
]
}
os.path.joinwill join (dir1, dir2, dir3, ..., file) into a path. You don't want this. Just prependos.environ['ENV']tofile_suffixwithos.environ['ENV'] + file_suffix.mkdir /tmp/staging? You can't create a file in a directory that doesn't exist.