954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

printing to file-variable file name

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.

breatheasier
Light Poster
46 posts since Feb 2009
Reputation Points: 11
Solved Threads: 2
 

Apologies, I figured it out, simply:

output = open('output''%s' % (a), 'w')
breatheasier
Light Poster
46 posts since Feb 2009
Reputation Points: 11
Solved Threads: 2
 

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.

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

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

thanks ou

xopenex
Newbie Poster
24 posts since Feb 2012
Reputation Points: 10
Solved Threads: 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.

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

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

xopenex
Newbie Poster
24 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You