Create a file name using Variables in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
3 min

banner

# Table of Contents

  1. Create a file name using Variables in Python
  2. Create a file name using Variables with the addition operator
  3. Create a file name using Variables using str.format()

# Create a file name using Variables in Python

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.

main.py
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')

create file name using variables

The code for this article is available on GitHub

We used a formatted string literal to create a file name using variables.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
main.py
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}.csv' print(result) # ๐Ÿ‘‰๏ธ bobbyhadz.csv
The code for this article is available on GitHub

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.

# Creating a file name that contains an integer

Here is an example where we create a file name that contains an integer.

main.py
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')

create file name that contains integer

The code for this article is available on GitHub

Formatted string literals also enable us to use expressions inside the curly braces.

# Creating a file name with a timestamp

Here is an example that uses the time.time() method to construct a file name.

main.py
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')

create file name with timestamp

The code for this article is available on GitHub

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.

# Create a file name using Variables with the addition operator

An alternative approach is to use the addition (+) operator.

The addition (+) operator can be used to concatenate strings with strings stored in variables.

main.py
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'])

create file name using variables with addition operator

The code for this article is available on GitHub

When the addition (+) operator is used with strings, it concatenates them.

main.py
print('ab' + 'cd') # ๐Ÿ‘‰๏ธ abcd
However, when you use the addition operator, you have to make sure that the values on the left and right-hand sides are strings.

If the variable stores an integer, use the str() class to convert it to a string.

main.py
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.

# Create a file name using Variables using str.format()

You can also use the str.format() method.

The string the method is called on can contain replacement fields specified using curly braces.

main.py
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')

create file name using variables with str format

The code for this article is available on GitHub

The str.format() method performs string formatting operations.

main.py
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.

main.py
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.

main.py
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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev