0
import os

file = open('henryTheSquareEaredCat.txt', mode = 'r')

newLines = []
for line in file:
    if 'square' in line :
        newLine = line.replace('square', 'pentagon')
        newLines.append(newLine)
    elif 'Square' in line:
        newLine = line.replace('Square', 'Pentagon')
        newLines.append(newLine)
    else:
        newLines.append(line)
file.close()

print(newLines)

with open('henryThePentagonEaredCat.txt', mode='w') as newFile:
    for newLine in newLines:
        newFile.write(newLine)
newFile.close()

correct = False
while not correct:
    keep = input('Would you like to keep the newly created file(Y or N)?')
    if keep == 'y' or 'Y':
        correct = True
    elif keep == 'n' or 'N':
        os.remove('henryThePentagonEaredCat.txt')
        print('The newly created file was successfully deleted')
        correct = True
    else:
        print('That is not a valid entry please try again')

The goal of this program as to go through the file and replace the word square with pentagon. This worked correctly, but afterwards I wanted to ask the user if they wanted to keep the newly created file and I am having some errors. Firstly when I enter 'N' or 'n' the file is not actually removed and the program ends, secondly when I enter something random like 'xyz' the program also ends, but as correct is still False it should run through the loop again.

Z. Young
  • 27
  • 2

0 Answers0