bluethundr
bluethundr

Reputation: 1325

Include variable in text string in Python

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?

Upvotes: 1

Views: 861

Answers (5)

scomes
scomes

Reputation: 1846

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

Upvotes: 3

BoarGules
BoarGules

Reputation: 16952

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.

Upvotes: 1

Richard Lenkiewicz
Richard Lenkiewicz

Reputation: 59

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)

Upvotes: 1

OSainz
OSainz

Reputation: 647

Give a look to: Python String Formatting Best Practices

Upvotes: 1

Parzibyte
Parzibyte

Reputation: 1598

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'

Upvotes: 1

Related Questions