Reputation: 323
I have a list below as list of names and want to use it as files names using loop.
name = [tina, vans, john, sam, victory]
using for loops i want to open files list below
for i in name:
a=open('tina.txt')
b=open('vans.txt')
c=open('john.txt')
d=open('sam.txt')
e=open('victory.txt')
sorry i know this is not correct code but i want to do something like this for my code to be. Can anyone please help me to get it right. THanks
Upvotes: 0
Views: 43
Reputation: 10624
Try the following (assuming that the scope of 'a' ends after each iteration, let me know otherwise):
for i in name:
a = open(f'{i}.txt')
If you have a list of lists (as per your question in comments) you can do the following:
for i in name:
for k in i:
a = open(f'{k}.txt')
Upvotes: 1
Reputation:
name = [tina, vans, john, sam, victory]
You can iterate over the list using for loop. Then, you can use f-strings
to open the file.
for new in name:
with open(f'{new}.txt','a') as file:
#some.code
Upvotes: 0
Reputation: 1
So, basically you need this array:
names = ['tina', 'vans', 'john', 'sam', 'victory']
Then you can loop
for name in names:
with open('{name}.txt'.format(name=name), 'r') as file:
# do something
Upvotes: 0
Reputation: 90
I'm not sure whether that's what you're trying to do, but here something to start with:
names = ['tina', 'vans', 'john', 'sam', 'victory']
opened_files = []
for next_name in names:
opened_files.append(open(f'{next_name}.txt', 'r')) # 'r' in case you just want to read
Upvotes: 0