0

I have a list with folder names, for which I need to create directories in the current location and copy files into those created directories. Because files need to be copied to correct directories I am using a loop to go over each folder name in the list, create a directory based on the folder name and then copy files into it. Creating directories based on elements in the list is not a problem. The problem for me is how to capture those created directories in each loop iteration so that I can use it in my path when copying files in the next step.

Here is what I've tried:

dir = ['aaa','bbb')
for dir in dir_list:
    print os.mkdir(path)

Folders are successfully created in current working directory during loop execution. But I also need to capture its names. I have printed results which shows that os.mkdir returns "None". How can I get created directory names in the loop instead of "None" object?

zwornik
  • 329
  • 7
  • 15

1 Answers1

1

As mentioned in the comments, the names of the folders are the paths you pass to os.kdir(). However, you can also directly copy the files to the folders just after creating the directory/ folder with the help of shutil. This can be done like in the following:

import os 
import shutil


root    = "root/"
folders = ['path_to_dir/dir1', 'path_to_dir/dir2', 'path_to_dir/dir3']
fnames  = ['path_to_file/file1','path_to_file/file2','path_to_file/file2']

for folder in folders:
    try: 
        os.makedir(root + folder)
    except: 
        print("Error creating folder: ", folder)

    for fname in fnames:
        try:
            src_path = root + fname
            dst_path = root + folder + "/" + fname.split("/")[-1]

            shutil.copyfile(src_path, dst_path)
        except:
            print("Couldn't copy file: ", fname)
SuperKogito
  • 2,998
  • 3
  • 16
  • 37
  • Thanks for the tips. I cannot use "shutil" cause I am copying files from Hadoop but your answer worked OK after adaptation to my case. – zwornik May 08 '19 at 11:31
  • Glad it helped :) As a work-around `shutil` you can use `os.popen`, or `os.system` or `subprocess`. In this [post](https://stackoverflow.com/questions/123198/how-do-i-copy-a-file-in-python), the answer by @kmario23 gives a wide variety of alternatives to `shutil`. – SuperKogito May 08 '19 at 11:39