Question

I'm trying to create an output folder/file for a batch script I'm running on every file in a folder. I would like it if when I found all the files or folders in the targetFolder I could create a targetFolder_output, and if targetFolder has a folder, anotherFolder, in it I could create anotherFolder_output in targetFolder_out.

So in the end I have C:\targetFolder\anotherFolder and it's duplicate C:\targetFolder_output\anotherFolder_output

I plan to do this with all of the files in there, but I think if I can get over this folder hurdle, I can handle the file one.

import os

targetFolder = "C:\\Users\\MyUserName\\Desktop\\tests"
outputFolder = targetFolder + "_output"

# Iterate over everything in the targetFolder
for directory, subdirectories, files in os.walk(targetFolder): 
    folderBasename = (os.path.basename(directory) )

    if not os.path.exists(outputFolder + "\\" + folderBasename + "_output"):
        os.makedirs(outputFolder + "\\" + folderBasename + "_output")

So far all this is doing is making a folder on my desktop "tests_output" with the folders:
tests_output\tests_output
tests_output\level2_output
tests_output\level3_output

What I would like to see is:
tests_output\level2_output\level3_output

Any help will be very much appreciated!

Was it helpful?

Solution

import os
class FCopy(object):
    def __init__(self, source):
        self.source = source
        self.target = os.path.join(source, '_output')
        if not os.path.exists(self.target):
            os.makedirs(os.path.abspath(self.target))
        self.lf, self.ld = [], []

    def walk(self, path):
        for x in (os.path.join(path, x) for x in os.listdir(path)):
            if x == self.target:continue
            if os.path.isfile(x):
                self.lf.append(x)
            elif os.path.isdir(x):
                self.ld.append(x)
                self.walk(x)
            #extra code if you want to handle symlinks

    def do(self):
        #if thats all you want,
        #code this directly in walk
        self.walk(self.source)

        for x in self.ld:
            x = x.replace(self.source, self.target)
            os.makedirs(x)
        for x in self.lf:
            x = x.replace(self.source, self.target)
            with open(x, 'w') as f:pass

f = FCopy('C:\\PerfLogs\\w\\tmp\\codemirror')
f.do()

You may play with ifexists and so on. If all you want is double the structure of source, then you could move the creation of files/dirs in walk, in corresponding if...else P.S.: ignore my dir, I just make a test in it

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top