1

I am trying to solve this issue.

I have a list like that:

  g = ['hey','man','sup']

and i want 3 different text files like "hey.txt","man.txt","sup.txt".

I used;

f = open('hey.txt','w')
sys.stdout = f
....

but is there a way to do it like that?;

for x in range(3):
    f = open('g[x].txt','w')
Ş.Tufan
  • 17
  • 2

2 Answers2

5

Use string formatting:

for filename in g:
    f = open('{}.txt'.format(filename),'w')
Aleksandr Kovalev
  • 3,508
  • 4
  • 34
  • 36
  • 2
    `for x in g:` would be even better... especially if you replaced `x` with `filename` to get expressive variable names. – swenzel Sep 11 '15 at 09:25
5

you are almost there

Instead of this

for x in range(3):
    f = open('g[x].txt','w')

Do this:

for x in range(3):
    f = open(g[x]+'.txt','w')

The actual problem is 'g[x].txt' it is a string and it's value does not change during each iteration where as to get g elements we use g[x] which return a string which then can be appended with '.txt' to form the file name

You could use context manager to open the file object

i.e)

for x in range(3):
    with open(g[x]+'.txt','w') as f:

If you want both index and value then you could use enumerator

i.e.)

for index,value in enumerate(g):
    with open(value+'.txt','w') as f:
Community
  • 1
  • 1
The6thSense
  • 8,103
  • 8
  • 31
  • 65