0

Hi, I'm wanting my program to loop and create different files outputting at different stages in a while loop, I just can't work out how to make it happen!
here's a stupid example

while (a<10):
    a = a+1
    if (a=4) or (a=6):
        output = open('output'+a, 'w') #something like this?
        output.write('%s' % (a))		
	
        output.close()

in other words i want the value of a to also be in the title of a new file that is opened, for example it would be output4.dat, output6.dat. I'm sure this should be possible in python.

4
Contributors
5
Replies
7
Views
8 Years
Discussion Span
Last Post by xopenex
0

Apologies, I figured it out, simply:

output = open('output''%s' % (a), 'w')
0

Your example is really not stupid! Remember, even the best of us were stupid about Python at one time ...

a = 0
while a < 10:
    a = a + 1
    if a == 4 or a == 6:
        # create file for instance 'output4.dat'
        # only strings concatinate
        output = open('output'+str(a)+'.dat', 'w')
        # write the value to file (needs to be a string)
        output.write('%s' % (a))
        output.close()

The best way to learn is to study other folks code and experiment with it.

0

hello, how would i change the code here, to have python create variables that i can call later, instead of files?

thanks ou

0

hello, how would i change the code here, to have python create variables that i can call later, instead of files?

The best way is to create a dictionary instead of variables

from pprint import pprint

dic = dict()

for a in range(50):
    if a % 10 in (4, 6):
        dic["output%d" % a] = a
        
pprint(dic)

""" my output -->
{'output14': 14,
 'output16': 16,
 'output24': 24,
 'output26': 26,
 'output34': 34,
 'output36': 36,
 'output4': 4,
 'output44': 44,
 'output46': 46,
 'output6': 6}
"""

Edit: don't revive old threads, start a new one instead.

Edited by Gribouillis: n/a

0

thank you for the response Gribouillis! and i will be sure to start new threads instead! :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.