1

I am trying to include the date in the name of a file. I'm using a variable called 'today'.

When I'm using bash I can reference a variable in a long string of text like this:

today=$(date +"%m-%d-%y")
output_dir="output_files/aws_volumes_list"
ofile="$output_dir"/aws-master-ebs-volumes-list-$today.csv

How can I achieve the same thing in python? I tried to do this, but it didn't work:

today = datetime.today()
today = today.strftime("%B %d %Y")
output_file = '../../../output_files/aws_instance_list/aws-master-list-'today'.csv'

I tried keeping the today variable out of the path by using single quotes.

How can I include the date in the name of the file that I'm creating when using Python?

5 Answers 5

3

You can add the strings together or use string formatting

output_file = '../../../output_files/aws_instance_list/aws-master-list-' + today + '.csv'
output_file = '../../../output_files/aws_instance_list/aws-master-list-{0}.csv'.format(today)
output_file = f'../../../output_files/aws_instance_list/aws-master-list-{today}.csv'

The last one will only work in Python >= 3.6

Sign up to request clarification or add additional context in comments.

Comments

1

In Python you use + to concat variables.

today = datetime.today()
today = today.strftime("%B %d %Y")
output_file = '../../../output_files/aws_instance_list/aws-master-list-' + today +'.csv'

Comments

1

Give a look to: Python String Formatting Best Practices

Comments

1

Not quite sure if thats what you mean, but in python you can either simply add the strings together

new_string=str1+ str2

or something like

new_string='some/location/path/etc/{}/etc//'.format(another_string)

Comments

1

The closest Python equivalent to bash's

ofile="$output_dir"/aws-master-ebs-volumes-list-$today.csv

is

ofile=f'"{output_dir}"/aws-master-ebs-volumes-list-{today}.csv'

Only in Python 3.7 onwards.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.