0

I am currently working on some code that will look through multiple directories from an .ini file then print and copy them to a new directory. I ran into a problem where the for loop that prints the files only executes once when it is supposed to execute 5 times. How can i fix it so the for loop works every time it is called?

Code:

def copyFiles(path):
    rootPath = path
    print(rootPath)
    pattern = "*.wav"
    search = ""

    #searches the directories for the specified file type then prints the name
    for root, dirs, files in os.walk(rootPath):
        for filename in fnmatch.filter(files, pattern):
            print(filename)

def main():
    #opens the file containing all the directories
    in_file = open('wheretolook.ini', "r")

    #create the new directory all the files will be moved to
    createDirectory()

    #takes the path names one at a time and then passes them to copyFiles
    for pathName in in_file:
        copyFiles(pathName)

Output i get from running my code

The output should have the 0 through 4 files under every diretory.

Thank you for the help!

Božo Stojković
  • 2,893
  • 1
  • 27
  • 52
Austin
  • 3
  • 1
  • 1
    Could you please fix the code indentation of the sample you posted and maybe add the 'tree' of a directory (abridged version) – Sergey Jul 19 '16 at 22:39
  • Wild guess: does the `.ini` file come from Windows and are you running on some kind of Unix? – cdarke Jul 19 '16 at 22:59
  • Please use [`with`](http://stackoverflow.com/q/3012488/1394393) to open (and close) files. Also, `ini` is an inappropriate extension if your file is just a single path per line. [`ini`](https://en.wikipedia.org/wiki/INI_file) has a specific format. (No particular standard is *completely* adopted, but all common implementations use `[sections]` and `name=value` pairs at minimum.) – jpmc26 Jul 20 '16 at 00:11

1 Answers1

0

The pathName you get when iterating over the file has a newline character at the end for each line but the last. This is why you get the blank lines in your output after each path is printed.

You need to call strip on your paths to remove the newlines:

for pathName in in_file:
    copyFiles(pathname.strip())

You could be more restrictive and use rstrip('\n'), but I suspect getting rid of all leading and trailing whitespace is better anyway.

Blckknght
  • 100,903
  • 11
  • 120
  • 169