2

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'?

1
  • Use normal slashes in paths even for Windows (the same way the Unix souls do). Python accepts them happily. But definitely use the os.path.join() and the related functions. Commented Jul 11, 2012 at 6:41

2 Answers 2

3
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]))
Sign up to request clarification or add additional context in comments.

Comments

2

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))

2 Comments

So I changed the os.mkdir line to what you suggested, but now I'm getting an error that I cannot create a file when that file already exists. They're not the same though, because one's a folder and the other is a text file, right? Any ideas? Thanks.
@AdrianAndronic directory names and filenames can't overlap. (just fire up the windows file browser and try to create a directory with the same name as a file or vice-versa...Windows shouldn't let you do it).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.