Use a formatted string literal to create a filename using a variable, such asf'{variable}.txt'
. Formatted string literals allow us to include expressions and variables in a string by preceding 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 use formatted string literals to create filenames using variables.
Formatted string literals
f-strings
Let us include an expression in a string by prepending f in front of it.
var1 = 'fql' var2 = 'jiyik' result = f'{var1}{var2}.csv' print(result) # ????️ fqljiyik.csv
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 within curly braces.
This is an example of using thetime.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 use thetime.time()
method to get the number of seconds since the epoch.
We can also call functions directly between curly braces.
Another way is to use the additiveoperator.
Use additionOperators use variables to create file names, for example
file_name '.csv'
. The additionoperator can be used to concatenate a string with a string stored in a variable.
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(['www', 'jiyik', 'Com'])
When the additionoperator is used with strings, it concatenates them.
print('ab' + 'cd') # ????️ abcd
But
, when we use the addition operator, we have to make sure that the values on the left and right are strings.
If the variable stores an integer, use thestr()
function 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 sides of the addition operator need to be of compatible types.
This is not the case when using f-strings as they automatically handle the conversion for us.
We can also create file names using variables using thestr.format()
method.
Use thestr.format()
method to create file names using variables, for example'{}.txt '.format(file_name)
. The string on which this method is called 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')
str.format()
method performs string formatting operations.
first = 'fql' last = 'jiyik' result = "{}_{}.txt".format(first, last) print(result) # ????️ "fql_jiyik.txt"
The string calling this method can contain replacement fields specified using curly braces{}
.
The replacement field can also contain the name of the keyword argument.
first = 'fql' last = 'jiyik' result = "{f}_{l}.txt".format(f=first, l=last) print(result) # ????️ "fql_jiyik.txt"
We can also call a function to specify the value of the replacement field.
import time first = 'jiyik' result = "{}_{}.txt".format(first, int(time.time())) print(result) # ????️ "jiyik_1665817957.txt"
Please note that
, thestr.format()
method will automatically convert integers to strings when formatting.
Which method we choose is a matter of personal preference. I would use formatted string literals because I find them very readable and intuitive.
The above is the detailed content of How to use variables to create file names in Python. For more information, please follow other related articles on the PHP Chinese website!