T
T
Timebird2016-07-27 01:30:02
Python
Timebird, 2016-07-27 01:30:02

How to create lists with dynamically changing names?

To open a file with a variable name, use the command:

files = [open('textfile_number_{}.txt'.format(i), 'w') for i in list_with_numbers]

You need to create a bunch of lists with different names like this, something like this:
[list_for_new_freq_{}.format(i) = [] for i in len(files)]

However, this code is, of course, not correct. How to fix it to avoid using dictionaries?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
tema_sun, 2016-07-27
@Timebird

["list_for_new_freq_{}".format(i.name) for i in files]

3
3dr1aN, 2016-07-27
@3dr1aN

Maybe it's better to write in a dictionary?
If you still need to, use exec() for example.

A
abcd0x00, 2016-07-27
@abcd0x00

>>> numbers = (1, 2, 3)
>>> fnames = ('file{}.txt'.format(i) for i in numbers)
>>> files = [open(i, 'w', encoding='utf-8') for i in fnames]
>>> files
[<_io.TextIOWrapper name='file1.txt' mode='w' encoding='utf-8'>, <_io.TextIOWrapper name='file2.txt' mode='w' encoding='utf-8'>, <_io.TextIOWrapper name='file3.txt' mode='w' encoding='utf-8'>]
>>> [i.close() for i in files]
[None, None, None]
>>>

[[email protected] t]$ ls
file1.txt  file2.txt  file3.txt
[[email protected] t]$

In general, it is customary to open files through with. If there is no special need for manual opening and closing, then use with.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question