Issue
I'm trying to write a function that takes another function as an optional argument. I'm a little stuck (and confused) with the syntax. I want func2 to be an optional argument. So I only want it to work when I call it in func1. I want it to work as a filter function for when I have more complex file patterns. glob.glob(files + '/*')
can give all the files in the directories specified. (glob.glob(path + '/' + file_name + '*'))
can give more complex patterns, I'm just not sure how to implement it as an optional function argument. any help would be much appreciated!
import glob
def func1(dirs, func2):
if type(dirs) == list:
for files in dirs:
files = glob.glob(files + '/*')
print(files) # prints all of the file names in each directory given
if func2:
func2(file_name)
def func2(file_name):
if file_name in files:
print(file_name)
# (glob.glob(path + '/' + file_name + '*'))
func1(['C:\path\to\files1\', 'C:\path\to\files2\'], func2('test2'))
For this example assume \files1 contains 'test1.txt' and 'test2.txt' and files2 containts 'test1.jpg' and 'test2.jpg'. I want func1
to print the the path for test2.txt and test1.jpg.
Solution
The only difference is how you pass the function. You're currently passing the return
of func2('test2')
, you should just pass func2
. Also be sure to pass files
to func2, otherwise that won't be defined.
import glob
def func1(dirs, func2, another_variable):
if type(dirs) == list:
for files in dirs:
files = glob.glob(files + '/*')
print(files) # prints all of the file names in each directory given
if func2:
func2(another_variable, files)
def func2(file_name, files):
if file_name in files:
print(file_name)
# (glob.glob(path + '/' + file_name + '*'))
func1(['C:\path\to\files1\', 'C:\path\to\files2\'], func2, 'test_2')
Answered By - Nathan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.