How to Create Filenames with Variables in Python
Generating filenames dynamically using variables is a common task in Python.
This guide explores various techniques for creating filenames, including using f-strings, the addition operator (+
), and the str.format()
method. You'll learn how to combine strings, integers, and timestamps into file names.
Creating Filenames with s-strings
Formatted string literals (f-strings) provide a concise way to create dynamic filenames by embedding variables and expressions directly into a string.
file_name = 'example'
print(f'{file_name}.txt') # Output: example.txt
with open(f'{file_name}.txt', 'w', encoding='utf-8') as f:
f.write('first line' + '\n')
f.write('second line' + '\n')
- The f-string
f'{file_name}.txt'
inserts the value offile_name
variable and adds the literal.txt
string to it. - f-strings automatically take care of converting variable to a string format.
Creating Filenames with Integers
Use f-strings to also easily create a filename containing integer value:
file_name = 'example'
integer = 1234
print(f'{file_name}_{integer}.txt') # Output: 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')
- The curly braces
{}
in the f-string allows for the inclusion of expressions, and variables which can then be embedded in the resulting string.
Creating Filenames with Timestamps
You can call any function within the f-string expression:
import time
timestamp = int(time.time())
file_name = 'example'
print(f'{file_name}_{timestamp}.txt') # Output: example_1738622393.txt
with open(f'{file_name}_{timestamp}.txt', 'w', encoding='utf-8') as f:
f.write('first line' + '\n')
f.write('second line' + '\n')
- The
time.time()
method returns the current timestamp, which is then converted to an integer. - Then an f-string is used to create a dynamic filename with a timestamp.
Creating Filenames with the Addition Operator (+
)
The addition operator can be used to concatenate strings, but you need to explicitly convert integers to strings. This approach works well when all parts of the filename are already strings:
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(['tutorial', 'reference', 'com'])
- The
+
operator is used to concatenate a literal string with a string variable, creating a filename.
Remember to use str()
to convert other types to a string:
file_name = 123456
result = str(file_name) + '.csv'
print(result) # Output: 123456.csv
Creating Filenames with str.format()
The str.format()
method provides another approach to inserting variables into a string:
file_name = 'example'
print('{}.txt'.format(file_name)) # Output: 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 curly braces are replaced with the values passed to the
format()
method.
You can also use keyword arguments within str.format()
to create your filenames:
first = 'tutorial'
last = 'reference'
result = "{f}_{l}.txt".format(f=first, l=last)
print(result) # Output: tutorial_reference.txt
- This is useful if your format string has more than one placeholder and you want to specify which argument should be placed at each of the placeholders, using the keys from the named parameters in the format method call.