subhabrata.bane...@gmail.com writes:

> Dear Group,
>
> I am trying to open multiple files at one time. 
> I am trying to do it as,
>
>  for item in  [ "one", "two", "three" ]:
>        f = open (item + "world.txt", "w")
>        f.close()
>
> This is fine. But I was looking if I do not know the number of
> text files I would create beforehand, so not trying xrange option
> also.
>
> And if in every run of the code if the name of the text files have
> to created on its own.
>
> Is there a solution for this? 

I have trouble comprehending your question so I am going to guess a bit
– feel free to clarify your problem.

If you want to repeat a set of commands not for a certain number of
items but based on a condition take a look at the *while-loop*.  The
basic loop construct looks like this:

  while condition:
    do_stuff()

Now the problem: *While* your program still has stuff to do (you have to
come up with an appropiate condition) you want to write output to files.
The filenames will be a concatenation of a number counting the already
created files and a predifined string (say "world.txt").

(Is this a correct description of your problem? Again: feel free to
clarify.)

The following lines might get you closer to a solution:


  j = 1
  continue_to_open_files = True
  while continue_to_open_files:
    with open("%03iworld" % j, "w") as f:
      f.write("some content")
    if some_condition:
      continue_to_open_files = False
    j += 1


Alternativly /itertools.count/ allows using of the for-loop:

  import itertools
  for j in itertools.count(1):
    with open("%03iworld" % j, "w") as f:
      f.write("some content")
    if some_condition:
      break


Translating numbers represented by digits into words is another problem.

--
Felix Dietrich
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to