0

I am trying to replace all instances of a given string in a text file. I am trying to read the file line by line and then use the replace function, however it is just outputting a blank file instead of the expected. What could I be doing wrong?

file = input("Enter a filename: ")
remove = input("Enter the string to be removed: ")

fopen = open(file, 'r+')
lines = []

for line in fopen:
    line = line.replace(remove,"")

fopen.close()
Ampage Green
  • 148
  • 7
  • File modification. I could print the lines just fine, but for some reason was having trouble actually overwriting the initial data in the file. It would either append the new text at the end of the file or just completely blank the file. – Ampage Green Jun 20 '18 at 02:08

1 Answers1

3

Try this:

# Make sure this is the valid path to your file
file = input("Enter a filename: ")
remove = input("Enter the string to be removed: ")

# Read in the file
with open(file, "r") as file:
    filedata = file.read()

# Replace the target string
filedata = filedata.replace(remove, "")

# Write the file out again
with open(file, "w") as file:
    file.write(filedata)

Note: You might want to use with open syntax, the benefit is elaborated in this answer by Jason Sundram.