May-13-2019, 11:23 AM
Hi friends,
I am trying to loop through files and from each file delete the lines that contain the search keywords
It may not be syntactically correct as i borrowed code from here and there.
Please may a kind person have a look at this
thank you for your time and help
I am trying to loop through files and from each file delete the lines that contain the search keywords
import os def remove_line_from_file(filename, line_to_remove, dirpath=''): filename = os.path.join(dirpath, filename) temp_path = os.path.join(dirpath, 'temp.txt') with open(filename, 'r') as f_read, open(temp_path, 'w') as temp: search_keywords=['Car','Train'] # Delete all sentences that contain these words for line in f_read: if (any(map(lambda word: word in line, search_keywords))): if line.strip() == word: #f line.strip() == line_to_remove: continue temp.write(line) os.remove(filename) os.rename(temp_path, filename) directory = 'C:/Users/Home/Desktop/test/' dirpath, _, files = next(os.walk(directory)) for f in files: remove_line_from_file(f, line, dirpath)I dont get an error as such - but I cant work out why it doesnt work.
It may not be syntactically correct as i borrowed code from here and there.
Please may a kind person have a look at this
thank you for your time and help
:)
Python newbie trying to learn the ropes