Gasnot Sacha Gasnot Sacha - 3 months ago 7
Python Question

python - Write in different files created

I would like to create, let's say, 100 folders, and in each folder create a txt file. And I would like to write different things in each text file, because of some conditions. I can create the folders, and create the file in each folder. But by using with open('...') as f :, I am not able to write different things in each text file.

Here is the code to create the folders and the files. It works perfectly.

def createAndFillFolders():

for i in range(100):
dir_name = (('/home/pi/Project/folder_%s') % (i))
if os.path.exists(dir_name): # if the folder already exists
shutil.rmtree(dir_name) # then overwrite
os.makedirs(dir_name)
open(os.path.join(dir_name, "file_%s" % (i + 1)), "w")


But if now I want to write different things in each file, I can't find a way to do this properly.
I tried using os.path.join with open but it doesn't work when I use "open with(...) :

with open(os.path.join(dire_name,'/file_%s.txt' % (i + 1, i + 1), "w") as #("file_%i.txt" % (i + 1)):
("file_%i.txt" % (i + 1)).write("%i" %(i + 1))


I know this last part of code is completly false but it could help to understand what I would like to have.

So each folder_i has a file_i.txt file with "i" written inside.

Thanks for helping !!

Answer
def writeToFiles():

    for i in range(100):
        dir_name = (('/home/pi/Project/folder_%s') % (i))
        f = open(os.path.join(dir_name, "file_%s" % (i + 1)), "w")
        f.write(str(i))
        f.close()

This is one to do it I will prefer that you do that while creating your files and folder only for that you will do something like this:

def createAndFillFolders():

    for i in range(100):
        dir_name = (('/home/pi/Project/folder_%s') % (i))
        if os.path.exists(dir_name): # if the folder already exists
            shutil.rmtree(dir_name) # then overwrite
        os.makedirs(dir_name)
        f = open(os.path.join(dir_name, "file_%s" % (i + 1)), "w")
        f.write(str(i))
        f.close()

Let me know if you face any error, or is stuck somewhere.

Comments