Answer the question
In order to leave comments, you need to log in
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]
[list_for_new_freq_{}.format(i) = [] for i in len(files)]
Answer the question
In order to leave comments, you need to log in
Maybe it's better to write in a dictionary?
If you still need to, use exec() for example.
>>> 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]$
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question