Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

python - 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 the file name. (I'm fairly new to this, just trying to create scripts for more efficiency at my job - I looked at a ton of StackOverflow pages and some places around the web but couldn't find something relating to Python for this specific task)

I've converted the folders into a list of strings I can search the filenames for, however when I go to copy them over they all go into the first folder found. The exact piece of this I need help with is how to get the file to copy into the folder it found a string match for.

Essentially, "if any(x in dirName for x in list):", "move file to x".

Regarding sourceFolder and destFolder, these are variables gotten from user input earlier in the code. (sourceFolder contains the files, destFolder contains the subfolders I'm copying to)

EDIT: I have multiple subfolders in the destFolder, I can get the files to copy if they match a string, (if no match is present, they don't copy). However, when they do copy, they all go to the same subfolder.

list=[]

if var == "y": #Checks for 'Yes' answer
    for subdir, dirs, files in os.walk(destFolder):
        subdirName = subdir[len(destFolder) + 1:] #Pulls subfolder names as strings
        print subdirName
        list.insert(0, subdirName)
        print "Added to list"


for subdir, dirs, files in os.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)

            string = dirName #this is the string we're looking in
            if any(x in dirName for x in list):
                print "Found string: " + dirName
                shutil.copy2(os.path.join(subdir, file), destination)
            else:
                print "No String found in: " + dirName

EDIT 2: After some tweaking and outside help, here's what I ended up with as far as working code goes (For the sake of anyone who comes across this). Some of the variables changed names, but hopefully the structure is readable.

import shutil, os, re, stat from os import listdir from os.path import isfile, join

destKey = dict()

if var == "y": #Checks for 'Yes' answer
    for root, dirs, files in os.walk(destFolder):
        for dest_folder in dirs: #This is the folder, for each we look at
            destKey[dest_folder] = os.path.join(root, dest_folder) #This is where we convert it to a dictionary with a key

for sourceFile in os.listdir(sourceFolder):
    print ('Source File: {0}').format(sourceFile)
    sourceFileName = os.path.basename(sourceFile) #filename, no path
    for dest_folder_name in destKey.keys():
        if dest_folder_name in sourceFileName.split('-'): #checks for dest name in sourceFile
            destination = destKey[dest_folder_name]
            print "Key match found for" + dest_folder_name
            shutil.copy2(os.path.join(sourceFolder, sourceFile), destination)
            print "Item copied: " + sourceFile
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is how I would do the comparison:

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

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

So your code would look like this:

for subdir, dirs, files in os.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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...