How can I fix this so it adds an info.txt into each newly created folder, not in the parent folder?

Question:

I have this which makes directories and then creates txt files. But it creates the txt files in the main parent dir. I want one info.txt in each newly created folder. How can I fix?

import os

parent_dir = r"C:America"
text_file = r"C:dir.txt"
info_file = "info.txt"

with open(text_file, 'r', encoding='utf-8') as f:
    lines = f.read().splitlines()
    for line in lines:
        path = os.path.join(parent_dir, line)
        new_dir = os.mkdir(path)
        with open(path + info_file, 'w') as filehandle:
            filehandle.writelines('test')
Asked By: uncrayon

||

Answers:

You’ll want to use os.path.join() when creating that final filename too, instead of path + info_file.

If path doesn’t have a slash at the end, with e.g. path = "test" you’d get "testinfo.txt", which is a relative pathname for a file in the working directory – os.path.join() adds the delimiter if it isn’t there. (To be clear, in your case, if line is "test", path would end up being "C:Americatest", and adding info.txt to that, you’d get "C:Americatestinfo.txt".)

You may also wish to use os.makedirs() to create the full folder path, if necessary; os.mkdir() would raise an exception if an intermediate folder isn’t there, or if the target folder already is there.

with open(text_file, 'r', encoding='utf-8') as f:
    lines = f.read().splitlines()
    for line in lines:
        path = os.path.join(parent_dir, line)
        os.mkdir(path)
        info = os.path.join(path, info_file)
        with open(info, 'w') as filehandle:
            filehandle.writelines('test')
Answered By: AKX
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.