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.

Apologies, I figured it out, simply:

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

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.

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

thanks ou

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.