How to deal with multiple arguments in function? - python

What is correct way to filter out data from functions? Should I try to compress everything as much as possible (search_query) or should I filter through list everytime there is new argument that needs to be included (search_query2). More arguments I have, quicker I become more confused how to deal with this problem. Example:
import os
query = ""
my_path = os.getcwd()
def search_query(query, path, extensions_only=False, case_sensitive=False):
results = []
if extensions_only is True:
for f in os.listdir(path):
if case_sensitive:
if f.endswith(query):
results.append(os.path.join(path, f))
else:
if f.endswith(query):
results.append(os.path.join(path, f).lower())
elif case_sensitive is not True:
for f in os.listdir(path):
if query.lower() in f.lower():
results.append(os.path.join(path, f))
return results
results = search_query("_c", my_path)
print(results)
# Alternative way to deal with this
def search_query2(query, path, extensions_only=False, case_sensitive=False):
results = []
for f in os.listdir(path):
results.append(os.path.join(path, f))
if extensions_only:
filtered_lst = []
for part in results:
if part.endswith(query):
filtered_lst.append(part)
results = filtered_lst
if case_sensitive:
filtered_lst = []
for part in results:
if query in part:
filtered_lst.append(part)
results = filtered_lst
elif not case_sensitive:
filtered_lst = []
for part in results:
if query.lower() in part.lower():
filtered_lst.append(part)
results = filtered_lst
print(results)
return results
search_query2("pyc", my_path, case_sensitive=True)

There isn't a fits-all "correct" way to do things like this. Another option is making separate functions, or private sub-functions called by this one as a wrapper.
In your specific case there are ways of optimising what you want to do in order to make it more clear.
You do a lot of
x = []
for i in y:
if cond(i):
x.append(i)
y = x
This is known as a filter and python has a couple of ways of doing this in one line
y = list(filter(cond, y)) # the 'functional' style
or
y = [i for i in y if cond(i)] # comprehension
which make things a lot clearer. There are similar things for mappings where you write:
x = []
for i in y:
x.append(func(i))
y = x
# instead do:
y = list(map(func, y)) # functional
# or
y = [func(i) for i in y] # comprehension
We can also combine maps and filters:
x = list(map(func, filter(cond, y)))
x = [func(i) for i in y if cond(i)]
using these we can build up many filters and maps in a row whilst remaining very clear about what we are doing. This is one of the advantages of functional programming.
I've modified your code to use generator expressions which will only evaluate right at the end when we call list(results) saving a lot of wasted time making new lists each time:
def search_query2(query, path, extensions_only=False, case_sensitive=False):
results = (os.path.join(path, f) for f in os.listdir(path))
if extensions_only:
results = (part for part in results if part.endswith(query))
elif case_sensitive: # I'm pretty sure this is actually the logic you want
results = (part for part in results if query in part)
else:
results = (part for part in results if query.lower() in part.lower())
return list(results)

Do you want to filter all the same types of files? You can do this by using the glob module.
for example
import glob
# Gets all the images in the specified directory.
print(glob.glob(r"E:/Picture/*/*.jpg"))
# Gets all the .py files from the parent directory.
print glob.glob(r'../*.py')

I like to "prepare" my conditions at the start to get things nice and tidy and make it slighlty easier later on. Identify what effect the different arguments have on the code. In this instance, "case_sensitive" defines whethere you are using f.lower() or not, and "extensions" is defining your comparison method.
In this instance I would write something like this.
def search_query(query, path, extensions_only=False, case_sensitive=False):
results = []
for f in os.listdir(path):
if case_sensitive is True:
fCase=f.lower()
queryCase = query.lower()
elif case sensitive is False:
fCase = f
queryCase = query
if extensions_only is True:
if f.endswith(query):
results.append(os.path.join(path, f))
elif extensions_only is False:
if query in f:
results.append(os.path.join(path, f))
return results
results = search_query("_c", my_path)
print(results)
This allows me to define the impact which each result has on the function at a different level, without having them nested and a bit of a headache to keep track of!

Another possibility: You could just use a single conditional list comprehension:
def search_query2(query, path, extensions_only=False, case_sensitive=False):
files = [os.path.join(path, f) for f in os.listdir(path)]
result = [part for part in files
if (not extensions_only or part.endswith(query)) and
(query in part if case_sensitive
else query.lower() in part.lower())]
print(results)
return results
This may seem very "dense" and incomprehensible at first, but IMHO it makes it very clear (even clearer than your variable names) that all those conditions are merely filtering and never e.g. changing the actual elements of the result list.
Also, as noted in comments, you could just use a default-parameter extension="" instead of extensions_only (everything ends with "", and you could even pass a tuple of valid extensions). Either way, it is not entirely clear how the endswith and in constraints should play together, or whether the extension should also match case_sensitive or not. Further, files could probably be simplified as glob.glob(path + "/*").
But those points do not change the argument for using a single list comprehension for filtering the list of results.

Related

How to speed up several nested loops

I have nested for loops which are causing the execution of my operation to be incredibly slow. I wanted to know if there is another way to do this.
The operation is basically going through files in 6 different directories and seeing if there is a file in each directory that is the same before opening each file up and then displaying them.
My code is:
original_images = os.listdir(original_folder)
ground_truth_images = os.listdir(ground_truth_folder)
randomforest_images = os.listdir(randomforest)
ilastik_images = os.listdir(ilastik)
kmeans_images = os.listdir(kmeans)
logreg_multi_images = os.listdir(logreg_multi)
random_forest_multi_images = os.listdir(randomforest_multi)
for x in original_images:
for y in ground_truth_images:
for z in randomforest_images:
for i in ilastik_images:
for j in kmeans_images:
for t in logreg_multi_images:
for w in random_forest_multi_images:
if x == y == z == i == j == w == t:
*** rest of code operation ***
If the condition is that the same file must be present in all seven directories to run the rest of the code operation, then it's not necessary to search for the same file in all directories. As soon as the file is not in one of the directories, you can forget about it and move to the next file. So you can build a for loop looping through the files in the first directory and then build a chain of nested if statements: If the file exists in the next directory, you move forward to the directory after that and search there. If it doesn't, you move back to the first directory and pick the next file in it.
Convert all of them to sets and iterate through the last one, checking membership for all of the others:
original_images = os.listdir(original_folder)
ground_truth_images = os.listdir(ground_truth_folder)
randomforest_images = os.listdir(randomforest)
ilastik_images = os.listdir(ilastik)
kmeans_images = os.listdir(kmeans)
logreg_multi_images = os.listdir(logreg_multi)
files = set()
# add folder contents to the set of all files here
for folder in [original_images, ground_truth_images, randomforest_images, ilastik_images, kmeans_images, logreg_multi_images]:
files.update(folder)
random_forest_multi_images = set(os.listdir(randomforest_multi))
# find all common items between the sets
for file in random_forest_multi_images.intersection(files):
# rest of code
The reason this works is that you are only interested in the intersection of all sets, so you only need to iterate over one set and check for membership in the rest
You should check x == y before going in the nest loop. Then y == z etc. Now you are going over each loop way too often.
There is also another approach:
You can create a set of all your images and create an intersection over each set so the only elements which will remain are the ones that are equal. If you are sure that the files are the same you can skip that step.
If x is in all other list you can create your paths on the go:
import pathlib
original_images = os.listdir(original_folder)
ground_truth_images = pathlib.Path(ground_truth_folder) #this is a folder
randomforest_images = pathlib.Path(randomforest)
for x in original_images:
y = ground_truth_images / x
i = randomforest_images / x
# And so on for all your files
# check if all files exist:
for file in [x, y, i, j, t ,w]:
if not file.exists():
continue # go to next x
# REST OF YOUR CODE USING x, y, i, j, t, w,
# y, i, j, t, w, are now pathlib object, you can get s string (of its path using str(y), str(i) etc.

Repeating code when sorting information from a txt-file - Python

I'm having some problem with avoiding my code to repeat itself, like the title says, when I import data from a txt-file. My question is, if there is a smarter way to loop the function. I'm still very new to python in general so I don't have good knowledge in this area.
The code that I'm using is the following
with open("fundamenta.txt") as fundamenta:
fundamenta_list = []
for row in fundamenta:
info_1 = row.strip()
fundamenta_list.append(info_1)
namerow_1 = fundamenta_list[1]
sol_1 = fundamenta_list[2]
pe_1 = fundamenta_list[3]
ps_1 = fundamenta_list[4]
namerow_2 = fundamenta_list[5]
sol_2 = fundamenta_list[6]
pe_2 = fundamenta_list[7]
ps_2 = fundamenta_list[8]
namerow_3 = fundamenta_list[9]
sol_3 = fundamenta_list[10]
pe_3 = fundamenta_list[11]
ps_3 = fundamenta_list[12]
So when the code is reading from "fundamenta_list" how do I change to prevent code repetition?
It looks to me that your input file has records each as a block of 4 rows, so in turn is namerow, sol, pe, ps, and you'll be creating objects that take these 4 fields. Assuming your object is called MyObject, you can do something like:
with open("test.data") as f:
objects = []
while f:
try:
(namerow, sol, pe, ps) = next(f).strip(), next(f).strip(), next(f).strip(), next(f).strip()
objects.append(MyObject(namerow, sol, pe, ps))
except:
break
then you can access your objects as objects[0] etc.
You could even make it into a function returning the list of objects like in Moyote's answer.
If I understood your question correctly, you may want to make a function out of your code, so you can avoid repeating the same code.
You can do this:
def read_file_and_save_to_list(file_name):
with open(file_name) as f:
list_to_return = []
for row in f:
list_to_return.append(row.strip())
return list_to_return
Then afterwards you can call the function like this:
fundamenta_list = read_file_and_save_to_list("fundamenta.txt")

Ordering data from returned pool.apply_async

I am currently writing a steganography program. I currently have the majority of the things I want working. However I want to rebuild my message using multiple processes, this obviously means the bits returned from the processes need to be ordered. So currently I have:
Ok im home now I will put some actual code up.
def message_unhide(data):
inp = cv.LoadImage(data[0]) #data[0] path to image
steg = LSBSteg(inp)
bin = steg.unhideBin()
return bin
#code in main program underneath
count = 0
f = open(files[2], "wb") #files[2] = name of file to rebuild
fat = open("fat.txt", 'w+')
inp = cv.LoadImage(files[0][count]) # files[0] directory path of images
steg = LSBSteg(inp)
bin = steg.unhideBin()
fat.write(bin)
fat.close()
fat = open("fat.txt", 'rb')
num_files = fat.read() #amount of images message hidden across
fat.close()
count += 1
pool = Pool(5)
binary = []
''' Just something I was testing
for x in range(int(num_files)):
binary.append(0)
print (binary)
'''
while count <= int(num_files):
data = [files[0][count], count]
#f.write(pool.apply(message_unhide, args=(data, ))) #
#binary[count - 1] = [pool.apply_async(message_unhide, (data, ))] #
#again just another few ways i was trying to overcome
binary = [pool.apply_async(message_unhide, (data, ))]
count += 1
pool.close()
pool.join()
bits = [b.get() for b in binary]
print(binary)
#for b in bits:
# f.write(b)
f.close()
This method just overwrites binary
binary = [pool.apply_async(message_unhide, (data, ))]
This method fills the entire binary, however I loose the .get()
binary[count - 1] = [pool.apply_async(message_unhide, (data, ))]
Sorry for sloppy coding I am certainly no expert.
Your main issue has to do with overwriting binary in the loop. You only have one item in the list because you're throwing away the previous list and recreating it each time. Instead, you should use append to modify the existing list:
binary.append(pool.apply_async(message_unhide, (data, )))
But you might have a much nicer time if you use pool.map instead of rolling your own version. It expects an iterable yielding a single argument to pass to the function on each iteration, and it returns a list of the return values. The map call blocks until all the values are ready, so you don't need any other synchronization logic.
Here's an implementation using a generator expression to build the data argument items on the fly. You could simplify things and just pass files[0] to map if you rewrote message_unhide to accept the filename as its argument directly, without indexing a list (you never use the index, it seems):
# no loop this time
binary = pool.map(message_unhide, ([file, i] for i, file in enumerate(files[0])))

Recursively list all files in directory (Unix)

I am trying to list all files a directory recursively using python. I saw many solutions using os.walk. But I don't want to use os.walk. Instead I want to implement recursion myself.
import os
fi = []
def files(a):
f = [i for i in os.listdir(a) if os.path.isfile(i)]
if len(os.listdir(a)) == 0:
return
if len(f) > 0:
fi.extend(f)
for j in [i for i in os.listdir(a) if os.path.isdir(i)]:
files(j)
files('.')
print fi
I am trying to learn recursion. I saw following Q?A, but I am not able to implement correctly it in my code.
Python recursive directory reading without os.walk
os.listdir return only the filename (without the full path)
so I think calling files(j) will not work correctly.
try using files(os.path.join(dirName,j))
or something like this:
def files(a):
entries = [os.path.join(a,i) for i in os.listdir(a)]
f = [i for i in entries if os.path.isfile(i)]
if len(os.listdir(a)) == 0:
return
if len(f) > 0:
fi.extend(f)
for j in [i for i in entries if os.path.isdir(i)]:
files(j)
I tried to stay close to your structure. However, I would write it with only one loop over the entries, something like that:
def files(a):
entries = [os.path.join(a,i) for i in os.listdir(a)]
if len(entries) == 0:
return
for e in entries:
if os.path.isfile(e):
fi.append(e)
elif os.path.isdir(e):
files(e)
Another way is not to use a global variable. This can be done using the following. Just modified the previous answer a little bit. I think this might be a little more readable ...
def files(a):
entries = [os.path.join(a,i) for i in os.listdir(a)]
folders = filter(os.path.isdir, entries)
normalFiles = filter(os.path.isfile, entries)
for f in folders:
normalFiles += files(f)
return normalFiles

removing file names from a list python

I have all filenames of a directory in a list named files. And I want to filter it so only the files with the .php extension remain.
for x in files:
if x.find(".php") == -1:
files.remove(x)
But this seems to skip filenames. What can I do about this?
How about a simple list comprehension?
files = [f for f in files if f.endswith('.php')]
Or if you prefer a generator as a result:
files = (f for f in files if f.endswith('.php'))
>>> files = ['a.php', 'b.txt', 'c.html', 'd.php']
>>> [f for f in files if f.endswith('.php')]
['a.php', 'd.php']
Most of the answers provided give list / generator comprehensions, which are probably the way you want to go 90% of the time, especially if you don't want to modify the original list.
However, for those situations where (say for size reasons) you want to modify the original list in place, I generally use the following snippet:
idx = 0
while idx < len(files):
if files[idx].find(".php") == -1:
del files[idx]
else:
idx += 1
As to why your original code wasn't working - it's changing the list as you iterator over it... the "for x in files" is implicitly creating an iterator, just like if you'd done "for x in iter(files)", and deleting elements in the list confuses the iterator about what position it is at. For such situations, I generally use the above code, or if it happens a lot in a project, factor it out into a function, eg:
def filter_in_place(func, target):
idx = 0
while idx < len(target):
if func(target[idx)):
idx += 1
else:
del target[idx]
Just stumbled across this old question. Many solutions here will do the job but they ignore a case where filename could be just ".php". I suspect that the question was about how to filter PHP scripts and ".php" may not be a php script. Solution that I propose is as follows:
>>> import os.path
>>> files = ['a.php', 'b.txt', 'c.html', 'd.php', '.php']
>>> [f for f in files if os.path.splitext(f)[1] == ".php"]

Categories