How can I iterate over files in a given directory?

Python 3.6 version of the above answer, using os – assuming that you have the directory path as a str object in a variable called directory_in_str: import os directory = os.fsencode(directory_in_str) for file in os.listdir(directory): filename = os.fsdecode(file) if filename.endswith(“.asm”) or filename.endswith(“.py”): # print(os.path.join(directory, filename)) continue else: continue Or recursively, using pathlib: from pathlib import … Read more

Calling remove in foreach loop in Java [duplicate]

To safely remove from a collection while iterating over it you should use an Iterator. For example: List<String> names = …. Iterator<String> i = names.iterator(); while (i.hasNext()) { String s = i.next(); // must be called before you can call i.remove() // Do something i.remove(); } From the Java Documentation : The iterators returned by … Read more

Why can’t I iterate twice over the same data?

Iterators (e.g. from calling iter, from generator expressions, or from generator functions which yield) are stateful and can only be consumed once, as explained in Óscar López’s answer. However, that answer’s recommendation to use itertools.tee(data) instead of list(data) for performance reasons is misleading. In most cases, where you want to iterate through the whole of … Read more

How to build a basic iterator?

Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__() and __next__(). The __iter__ returns the iterator object and is implicitly called at the start of loops. The __next__() method returns the next value and is implicitly called at each loop increment. This method raises a StopIteration exception … Read more

tech