1

I am starting with Python, and trying to make a function. The one i am in trouble is:

#~ this function should make a directory only if it doesn't exist
def make_dir(directoryname):
    if not os.path.exists(directoryname):
       return os.makedirs(directoryname)
    else: 
        print "la carpeta %s ya existe" %(directoryname)

What i want to know is if it is possible to give multiple inputs like

def make_dir(a,b,c,d,r)  #where a,b,c,d,r are directory names.

and how can i do it.

I apologize if it is an obvious question.

3 Answers3

3

Python has specific syntax for this. It is commonly referred to as *args. When Python sees this in a function definition, it allows the function caller to pass in a variable amount of arguments to the function.

The variable used in the *args syntax - which is a tuple - can then be used to access the arguments. In your case you can simply loop over the arguments and process them accordingly.

def make_dir(*dirs):
    for directory in dirs:
        if not os.path.exists(directory):
            return os.makedirs(directory)
        else:
            print "la carpeta %s ya existe" %(directory)

It is important to note you may name the args in *args anything you want. I renamed it dirs(short for directories). And while it is common practice to simply name it *args, in my opinion it is much better to rename it to fit each specific case. That way, you can clearly convey what kind of arguments your function expects.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
1

Either pass your variables as a sequence such as a tuple or list. Or use the splat operator * to unpack a variable amount of arguments.

i.e.

def foo(*args):
    return args

Sample Output:

>>> foo(1, 2, 3)
(1, 2, 3)
ospahiu
  • 3,465
  • 2
  • 13
  • 24
0

You can use a variable arguments variable with *directorynames and use a for loop in the function:

import os

def make_dir(*directorynames):
    for dir_ in directorynames:
        if not os.path.exists(dir_):
            return os.makedirs(dir_)
        else: 
            print("la carpeta %s ya existe" %(dir_))

Regards.

TC29
  • 1
  • 2