This function allows us to define which lines are copied by passing a function to it - which can be done on the fly with lambda functions. By default it always copies everything.
def copy_lines(source_file: str, target_file: str, criterion= lambda x: True):
with open(source_file) as source, open(target_file, "w") as target:
for line in source:
# Remove any whitespace from beginning and end of line
line = line.strip()
if criterion(line):
target.write(line + "\n")
# Some examples
if __name__ == "__main__":
# If the third parameter is not given, copy all lines
copy_lines("first.txt", "second.txt")
# Copy all non-empty lines
copy_lines("first.txt", "second.txt", lambda line: len(line) > 0)
# Copy all lines which contain the word "Python"
copy_lines("first.txt", "second.txt", lambda line: "Python" in line)
# Copy all lines which do not end in a full stop
copy_lines("first.txt", "second.txt", lambda line: line[-1] != ".")Something like this for a CLI seems pretty great.
For example, use the following to filter a list based on another func:
def search(products: list, criterion: callable):
return [product for product in products if criterion(product)]