Python 3.6 Define a function (not a script) called grep_to_file() which takes tw
ID: 3732384 • Letter: P
Question
Python 3.6
Define a function (not a script) called grep_to_file() which takes two filenames (the "source and the "destination") and a search string. The function should search through the source file for lines that contain the search string. Any line that contains the search string should be written to the destination file, and any line that doesn't contain the search string should not be written. If the function succeeds, it should return True. If an OSError is raised while working with either file, the function should return False. Put this function definition into your lab9.py script. Since this is a function that doesn't interact with the user, you should not be getting user input at any point in time. In particular, this means that you should not be using a while loop to get user input as you did in the previous three problems. If an OSError happens, you should just return False I have the same cow.txt file from above in the same directory as my script. Also, this directory also contains a subdirectory named folder. Here is a transcript of my version of grep_to_file() in action: RESTART >>>grep_to_file ("coww.txt","cow2.txt","ow") False >>>grep_tofile("cow.txt","cow2?txt","ow") False >>>grep to file (" cow.txt", "folder", "Ow") False >>>grep_tofile("cow.txt","cow2.txt","ow") True In the first example, an error was raised when trying to open the source file coww.txt (there is no such file). In the second example, an error was raised when trying to open the destination file cow2?txt (you can't create a file with a question mark in the name on a Windows* system). The third example ran into a problem because I tried to use the directory folder as a file This command would probably work fine on a Mac. In the last example, a new file cow2.txt was created with the following content: I have never seen a purple cow, But l can tell you anynow,Explanation / Answer
def grep_to_file(f1, f2, word): try: with open(f1, 'r') as fr, open(f2, 'w') as fw: for line in fr: if word in line: fw.write(line) return True except: return False grep_to_file('cow.txt', 'cow2.txt', 'ow')
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.