In python using beginners methods (no custom classes etc) and small files - How do I have a user find and replace bad information in a text file? My instructor says: The program will READ in data from a text file named StudyHours.txt. The user corrects any bad data. The program updates the information in StudyHours.txt file. For example if the file contains a letter grade of K which is not a possible letter grade. StudyHours.txt contains the following data: first line full name second line number of credits third line grade desired for each class Example format StudyHours.txt file Aaron RODgers 12 A Tom brady 9 K philip Rivers apple c Joe Theismann 15 B I need to show the user the contents of the file, have them enter in corrections, and then update the file with the correct information with the bad information deleted.
In python using beginners methods (no custom classes etc) and small files -
How do I have a user find and replace bad information in a text file? My instructor says:
- The program will READ in data from a text file named StudyHours.txt. The user corrects any bad data. The program updates the information in StudyHours.txt file. For example if the file contains a letter grade of K which is not a possible letter grade.
StudyHours.txt contains the following data:
- first line full name
- second line number of credits
- third line grade desired for each class
Example format StudyHours.txt file
Aaron RODgers
12
A
Tom brady
9
K
philip Rivers
apple
c
Joe Theismann
15
B
I need to show the user the contents of the file, have them enter in corrections, and then update the file with the correct information with the bad information deleted.
So far I have this:
import os
def main():
found = False
badFile = open('StudyHours.txt', 'r')
print(badFile.read())
search = input('Enter what you want to change: ')
newInfor = input('Enter the new info: ')
descr = badFile.readline()
while descr != '':
credit = str(badFile.readline())
descr = descr.rstrip('\n')
grade = str(badFile.readline())
credit = credit.rstrip('\n')
if descr == search:
tempFile.write(descr +'\n')
tempFile.write(str(newInfor) + '\n')
found = True
else:
tempFile.write(name + '\n')
tempFile.write(str(credit) + '\n')
descr = badFile.readline()
badFile.close()
tempFile.close()
os.rename('temp.txt', 'StudyHours2.txt')
if found:
print('The file has been updated.')
else:
print('That item was not found in the file.')
main()
Trending now
This is a popular solution!
Step by step
Solved in 2 steps with 1 images