Search code examples
pythonpython-2.7file-writinglistiterator

Script executing fine, but not writing to any files in specified directory


I am trying to write a script that will iterate through a specified directory, and write to any .txt files with a new string.

Edited after reading Lev Levitsky's explanation

import os

x = raw_input("Enter the directory path here: ")

def rootdir(x):
    for dirpaths, dirnames, files in os.walk(x):
        for filename in files:
            try:
                with open(os.paths.join(dirpaths, filename 'a')) as f:
                    f.write("newline")
            except:
                print "Directory empty or unable to open file"
            return x
rootdir(x)

The script executes, however I get my "Directory empty or unable to open file" exception.

Thanks in advance for any input.


Solution

  • If this is the whole script, then your function is never called, so no wonder nothing happens to the files. You need to actually call the function with the user-provided path:

    rootdir(x)
    

    Other issues I see with your code:

    • The function will erase the text file's content and replace it with "newline". That is because you open the file in write mode. Consider using append mode ('a') instead.

    • There is no os.dirpaths. You need os.path.join(dirpaths, filename). Also, 'w' is an argument to join, but it should be an argument to open. So in fact the files will be opened in read mode and with incorrect names, resulting in an error.

    • Finally, because of the return statement inside the loop body, the function will return after processing just one file, without touching the rest.