PYTHON 1. Write a script that asks the user to type in a source* filename and a
ID: 3676818 • Letter: P
Question
PYTHON
1. Write a script that asks the user to type in a source* filename and a destination* filename; opens both files; loops through the contents of the source file line-by-line, writing each one to the destination file; and then closes both files. Make sure that all work with the files happens inside of a try block. If an IOError occurs, the script should print a message saying that there was an error working with one of the files and ask the user to enter in the filenames again. You may implement this with either a while loop with .readline(), or a for loop, but the script must loop through the source file line-by-line; you may not use .read() or .readlines().
2. Define a function 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 IOError is raised while working with either file, the function should return False. 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.
Explanation / Answer
Answer for problem#1
--------------------------------------------------------
isCompleted = 0;
while(isCompleted == 0):
try:
srcFile = input ("Please enter source file name:")
destFile = input ("Please enter destination file name:")
#open input file
inputFile = open(srcFile, "r")
#open output file
outputFile = open(destFile, "w")
#Write each line to destination
for line in inputFile:
outputFile.write(line)
## close the file after reading the lines.
inputFile.close()
outputFile.close()
isCompleted = 1
#catch IO Exception
except IOError as e:
print (" there was an error working with one of the files. Please enter details again ")
isCompleted = 0
except:
print (" Unexpected error: ")
----output---------------
Please enter source file name:Personsdjfkd.py
Please enter destination file name:person.txt
there was an error working with one of the files. Please enter details again
Please enter source file name:Person.py
Please enter destination file name:Persontxt.txt
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.