Python Forum
How to open and write into several files - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to open and write into several files (/thread-9970.html)



How to open and write into several files - kazimahmet - May-07-2018

Hi all, since I'm new in Python, sorry for my easy question but I'd like to open new files in a loop lets say 4 new files which are writable and defined in a loop using for i in range(0,4) and then I want to write some data inside of them.

For example, if I had an only file named as controlpointsdata, the below code is ok

f=open("controlpointsdata","w")
but now I have 4 files and I want it to be written as

a=[i for i in range(0,4)]
f=[0 for i in range(0,4)]
for i in range(0,4):
f[i]=open("controlpointsdata_i","w")
f[i].write(a[i])
f[i].close()
The question is how could I open the files named as ctrlptdata_0, ctrlptdata_1, ctrlptdata_2,ctrlptdata_3 since the above code does not work correctly.

Best Regards,
Ahmet


RE: How to open and write into several files - Larz60+ - May-07-2018

files = ['ctrlptdata_0', 'ctrlptdata_1', 'ctrlptdata_2', 'ctrlptdata_3']
for num, filename in enumerate(files):
    with open(filename, 'w') as fp:
        fp.write(num)



RE: How to open and write into several files - kazimahmet - May-07-2018

(May-07-2018, 12:27 PM)Larz60+ Wrote:
files = ['ctrlptdata_0', 'ctrlptdata_1', 'ctrlptdata_2', 'ctrlptdata_3']
for num, filename in enumerate(files):
    with open(filename, 'w') as fp:
        fp.write(num)

Thank you for your reply @Larz60+ . I have learnt enumerator() function with your help. However, if I have 300 files, producing a files list like that, is so time consuming, is there a way to handle that problem by defining the file names, parametrically ?


RE: How to open and write into several files - wavic - May-07-2018

You can use any expression as the first argument to open().
So all can be done into the loop:

for num in range(300):
    with open('ctrlptdata_{}'.format(num), 'w') as fp:
        fp.write(num)
If you have 300 files