May-18-2019, 02:35 PM
(This post was last modified: May-18-2019, 06:26 PM by michalmonday.)
#!/usr/bin/python3 import os import csv import pandas def extract_lines_from_files(filename, dirpath): filename = os.path.join(dirpath, filename) search_keywords = ['Apple','Pear','Cherry'] with open(filename, 'r',errors='ignore') as f: lines = [] # the file object must be read first for line in f.readlines(): # (word in line) expression returns either True or False if any((word in line) for word in search_keywords): # strip() removes "\n" (new line byte) lines.append(line.strip()) with open("a.csv",'a', newline='') as csv_file: # delimeter is what separates the values in the csv file # btw csv = "comma separated values" writer = csv.writer(csv_file, delimiter='|') writer.writerow(lines) directory = 'C:/Users/home/Desktop/files/' for root, dirs, files in os.walk(directory): # using only the files that end with .txt # this way the files could be in the same directory with the .py file for f in filter(lambda x: x.endswith('.txt'), files): extract_lines_from_files(f, directory)Contents of the "a.csv" file:
Output:Apple 1|Pear 1|Cherry 1
Apple 2|Pear 2|Cherry 2