Skip to content Skip to sidebar Skip to footer

How Do I Copy Files Into Folders Based On The File Containing The Folder Name?

Python Version: 2.7.13 OS: Windows So I'm writing a script to copy files of various names into a specific folder based on the requirement that they contain the folder name inside t

Solution 1:

This is how I would do the comparison:

list = ["abc", "def", "ghi"]

dirname = "abcd"for x in list:
    if x indirname:
        print(dirname, x)

So your code would look like this:

for subdir, dirs, files inos.walk(sourceFolder):
    for file in files:
        dirName = os.path.splitext(file)[0] #This is the filename without the path
        destination = "{0}\{1}".format(destFolder, subdirName)

        for x in list:
            if x in dirName:
                print"Found string: " + dirName
                shutil.copy2(os.path.join(subdir, file), destination)
            else:
                print"No String found in: " + dirName

Does that solve the problem?

Solution 2:

I tried to keep it as close to your original code as possible. We throw any files that have the folder name in them into the corresponding folder. We don't repeat any files through our walk of all dirs using a set cache.

import os, shutil

dirs_ls = []

destFolder = 'Testing'for subdir, dirs, files in os.walk(destFolder):
    subdirName = subdir[len(destFolder) + 1:]  # Pulls subfolder names as strings
    dirs_ls.append(subdirName)

dirs_ls = filter(None, dirs_ls)

copied_files = set()
for subdir, dirs, files in os.walk(destFolder):
    for file_name in files:
        if file_name in copied_files:
            continue

        file_name_raw = file_name.split('.')[0]

        fordirin dirs_ls:
            ifdirnotin file_name_raw:
                continue
            shutil.copy2(os.path.join(destFolder, file_name), os.path.join(destFolder, file_name_raw))
            copied_files.add(file_name)

Directory structure prior to script run:

.
├── bro
├── bro.txt
├── foo
├── foo.txt
├── yo
└── yo.txt

Directory structure after script run:

.
├── bro
│   └── bro.txt
├── bro.txt
├── foo
│   └── foo.txt
├── foo.txt
├── yo
│   └── yo.txt
└── yo.txt

Solution 3:

Your solution is using any() to determine if the file matches to any of the subdirectories, and then it moves the file to the last value stored in subdir. And note how subdirName is last set in the previous loop, so its value will never change in the second loop. I'm seeing a few other issues as well. You need a list of subdirectory names but then you also need a list of complete relative paths, assuming destFolder and sourceFolder aren't the same and have subdirectories. It's also best to not overwrite basic types like list with your own variable name. Try this:

from os.path import dirname, join, splitext
from os import walk

dir_list = []
if var == "y": #Checks for 'Yes' answerfor subdir, dirs, files in walk(destFolder):
        dir_list.append(subdir)  # keeping the full path, not just the last directoryprint'Added "{0}" to the list'.format(subdir)

for subdir, dirs, files in walk(sourceFolder):
    for file in files:
        fname = splitext(file)[0]  # This is the filename without the pathfor dpath in dir_list:
            # Fetch last directory in the path
            dname = dirname(dpath)
            if dname in fname:
                # Directory name was found in the file name; copy the file
                destination = join(destFolder, dpath, file)
                shutil.copy2(join(subdir, file), destination)

I haven't tested the above, but that should give you an idea of how to make this work.

Post a Comment for "How Do I Copy Files Into Folders Based On The File Containing The Folder Name?"