define argument in command line for python os.walk script

Viewed 393

I am working on a larger script that walks through a directory structure to perform an action on each file.

I am having trouble figuring out how to pass the target directory as an argument in the command line (to be the starting point of the os.walk).

Can anyone advise on what I am doing wrong?

import os
import sys

def main():
    for root, dirs, files in os.walk(sys.argv[1])
      for item in files:
        print(items)

if __name__ == '__main__':
    main(sys.argv[1])
1 Answers

Yeah, your original call to main has main accepting no arguments:

import os
import sys

def main(): # this has 0 arguments, instead you included it inside of the func.
    for root, dirs, files in os.walk(sys.argv[1]):
      for item in files:
        print(items)

if __name__ == '__main__':
    main(sys.argv[1]) # likely the source of your error since main() has the argument inside the func.

If you would like main to have arguments:

def main(args): # any generic argument to be called
    for root, dirs, files, in os.walk(args):
        for item in files:
            print(items)
if __name__ = '__main__':
    main(sys.argv[1]) # specific argument called by function
Related