Adrian Andronic
Adrian Andronic

Reputation: 79

How to create a folder for each item in a directory?

I'm having trouble making folders that I create go where I want them to go. For each file in a given folder, I want to create a new folder, then put that file in the new folder. My problem is that the new folders I create are being put in the parent directory, not the one I want. My example:

def createFolder():
    dir_name = 'C:\\Users\\Adrian\\Entertainment\\Coding\\Test Folder'
    files = os.listdir(dir_name)
    for i in files:
        os.mkdir(i)

Let's say that my files in that directory are Hello.txt and Goodbye.txt. When I run the script, it makes new folders for these files, but puts them one level above, in 'C:\Users\Adrian\Entertainment\Coding.

How do I make it so they are created in the same place as the files, AKA 'C:\Users\Adrian\Entertainment\Coding\Test Folder'?

Upvotes: 2

Views: 2224

Answers (2)

Rakesh
Rakesh

Reputation: 82765

import os, shutil

for i in files:
  os.mkdir(os.path.join(dir_name , i.split(".")[0]))
  shutil.copy(os.path.join(dir_name , i), os.path.join(dir_name , i.split(".")[0]))

Upvotes: 3

Ned Batchelder
Ned Batchelder

Reputation: 375504

os.listdir(dir_name) lists only the names of the files, not full paths to the files. To get a path to the file, join it with dir_name:

os.mkdir(os.path.join(dir_name, i))

Upvotes: 2

Related Questions