Last updated: Apr 10, 2024
Reading timeยท3 min
Use a formatted string literal to create a file name using variables, e.g.
f'{variable}.txt'
.
Formatted string literals enable us to include expressions and variables
inside of a string by prefixing the string with f
.
file_name = 'example' print(f'{file_name}.txt') # ๐๏ธ example.txt with open(f'{file_name}.txt', 'w', encoding='utf-8') as f: f.write('first line' + '\n') f.write('second line' + '\n')
We used a formatted string literal to create a file name using variables.
f
.var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}.csv' print(result) # ๐๏ธ bobbyhadz.csv
Make sure to wrap expressions in curly braces - {expression}
.
An advantage of f-strings is that they automatically take care of converting non-string values to strings.
Here is an example where we create a file name that contains an integer.
file_name = 'example' integer = 1234 print(f'{file_name}_{integer}.txt') # ๐๏ธ example_1234.txt with open( f'{file_name}_{integer}.txt', 'w', encoding='utf-8' ) as f: f.write('first line' + '\n') f.write('second line' + '\n')
Formatted string literals also enable us to use expressions inside the curly braces.
Here is an example that uses the time.time()
method to construct a file name.
import time timestamp = int(time.time()) file_name = 'example' print(f'{file_name}_{timestamp}.txt') # ๐๏ธ example_1665817197.txt with open( f'{file_name}_{timestamp}.txt', 'w', encoding='utf-8' ) as f: f.write('first line' + '\n') f.write('second line' + '\n')
We used the time.time()
method to get the number of seconds since the epoch.
You can also directly call a function between the curly braces.
An alternative approach is to use the addition (+) operator.
The addition (+) operator can be used to concatenate strings with strings stored in variables.
import csv file_name = 'example' with open( file_name + '.csv', 'w', newline='', encoding='utf-8' ) as csvfile: csv_writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow(['Bobby', 'Hadz', 'Com'])
When the addition (+) operator is used with strings, it concatenates them.
print('ab' + 'cd') # ๐๏ธ abcd
If the variable stores an integer, use the str() class to convert it to a string.
file_name = 123456 result = str(file_name) + '.csv' print(result) # ๐๏ธ 123456.csv
This is necessary because the values on the left and right-hand sides of the addition operator need to be of compatible types.
This is not the case when using f-strings because they automatically take care of the conversion for us.
You can also use the str.format()
method.
The string the method is called on can contain replacement fields specified using curly braces.
file_name = 'example' print('{}.txt'.format(file_name)) # ๐๏ธ example.txt with open( '{}.txt'.format(file_name), 'w', encoding='utf-8' ) as f: f.write('first line' + '\n') f.write('second line' + '\n')
The str.format() method performs string formatting operations.
first = 'bobby' last = 'hadz' result = "{}_{}.txt".format(first, last) print(result) # ๐๏ธ "bobby_hadz.txt"
The string the method is called on can contain replacement fields specified
using curly braces {}
.
The replacement fields can also contain the name of a keyword argument.
first = 'bobby' last = 'hadz' result = "{f}_{l}.txt".format(f=first, l=last) print(result) # ๐๏ธ "bobby_hadz.txt"
You can also call functions to specify a value for a replacement field.
import time first = 'bobby' result = "{}_{}.txt".format(first, int(time.time())) print(result) # ๐๏ธ "bobby_1665817957.txt"
Notice that the str.format()
method automatically takes care of converting the
integer to a string when formatting.
Which approach you pick is a matter of personal preference. I'd use a formatted string literal because I find them quite readable and intuitive.
I've also written an article on how to use f-strings for conditional formatting.
You can learn more about the related topics by checking out the following tutorials: