Opening Multiple files at one time

sohcahtoa82 at gmail.com sohcahtoa82 at gmail.com
Mon Apr 20 16:04:45 EDT 2015


On Monday, April 20, 2015 at 5:00:15 AM UTC-7, subhabrat... at gmail.com wrote:
> 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? 
> 
> If anybody may please suggest. 
> 
> Regards,
> Subhabrata Banerjee.

Create a list and append each file object to the list.  Something like:

fileList = []
for item in ['one', 'two', 'three']:
    fileList.append(open(item + 'world.txt', 'w')

fileList will then have a list of open file objects.  Of course, later you'll have to close them all.  That would be as easy as:

for f in fileList:
    f.close()



More information about the Python-list mailing list