Home > Backend Development > Python Tutorial > How to use variables to create file names in Python

How to use variables to create file names in Python

王林
Release: 2023-05-02 20:31:11
forward
2317 people have browsed it

Use a formatted string literal to create a filename using a variable, such as f'{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')
Copy after login

We use formatted string literals to create filenames using variables.

Formatted string literalsf-stringsLet 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
Copy after login

How to use variables to create file names in Python

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')
Copy after login

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

This is an example of using 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')
Copy after login

How to use variables to create file names in Python

We use the time.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 additive operator.

Use variables with the addition operator to create file names

Use addition Operators use variables to create file names, for example file_name '.csv' . The addition operator 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'])
Copy after login

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

print('ab' + 'cd') # ????️ abcd
Copy after login

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 the str() function to convert it to a string.

file_name = 123456

result = str(file_name) + '.csv'

print(result) # ????️ 123456.csv
Copy after login

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 the str.format() method.

Use variables with addition operators to create file names

Use the str.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')
Copy after login

str.format() method performs string formatting operations.

first = 'fql'
last = 'jiyik'

result = "{}_{}.txt".format(first, last)
print(result)  # ????️ "fql_jiyik.txt"
Copy after login

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"
Copy after login

How to use variables to create file names in Python

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"
Copy after login

Please note that , the str.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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template