Write a program that implements the "replace all" function.

# Write a program to implement the "replace all" function.


def file_replace():
    file_name = input("Please enter the file name:")
    # Determine whether the input path or file exists
    try :
        f_read = open(file_name)
    except :
        print( "The path or file does not exist, please re-enter.")
        return file_replace() # If there is an error, return to calling the function

    rep_word = input("Please enter the word or character to be replaced:")
    new_word = input("Please enter a new word or character: ")

    content = [] # Create an empty list to store data
    count = 0 # Set the number of strings to be changed (initial value is 0)
    for eachline in f_read:
        if rep_word in eachline : # Determine whether the string or word to be changed is in this line
            count1 = eachline.count(rep_word) # The number of strings to be changed in each line
            eachline = eachline.replace(rep_word,new_word) # Change the string
            count += count1 # Self-increment the number of each line
        # Add to the list
        content.append(eachline)

    decide = input("\nThere are a total of %s in the file %s [%s]\nAre you sure you want to replace all [%s] with [%s]?\n[YES/NO]:\n"%(file_name,count,rep_word,rep_word,new_word) )

    if decide in ["YES","Yes","yes"]: # Decide if the user input contains these characters, then rewrite the content of the file
        f_write = open(file_name,"w")
        f_write.writelines(content)
        f_write.close()
        print("Change succeeded")
    else :
        print("You chose not to change.")
    f_read.close()


if __name__ == '__main__':
    file_replace()








Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325121702&siteId=291194637