4

I have a list of strings in a text file. The strings are morning, night, sun, moon. What I am trying to do is to replace one of these strings with another string. For example, I would input morning to remove and replace it with afternoon. I am getting an error saying "builtins.ValueError: list.remove(x): x not in list" when the string clearly is in the list.

def main():
    x = input("Enter a file name: ")
    file = open(x , "r+")
    y = input("Enter the string you want to replace: ")
    z = input("Enter the string you to replace it with: ")
    list = file.readlines()
    list.remove(y)
    list.append(z)
    file.write(list)
    print(file.read())

main()

If there is a better way of achieving the same results doing it another way, let me know. Thanks for the help!

2
  • You mean editing the file in place without creating another one ? Commented Apr 9, 2017 at 2:47
  • 3
    First, please do not ever call your variables list because list() is a built-in function. Second, your strings in list have line breaks '\n' at the end. You should strip them off before attempting the remove. Commented Apr 9, 2017 at 2:48

3 Answers 3

5

Here are some ideas:

  • The str.replace() function is the simplest way to replace strings, s.replace(y, z).

  • The re.sub() function will let you search for patterns and replace with strings: re.sub(y, z, s).

  • The fileinput module will allow you to modify in-place.

Here's one way to do it:

import fileinput
import re

with fileinput.input(files=('file1.txt', 'file2.txt'), inplace=True) as f:
    for line in f:
        print( re.sub(y, z, line) )

Here another idea:

  • Instead of processing line-by-line, just read the whole file in as a single string, fix it up, and then write it back.

For example:

import re

with open(filename) as f:
    s = f.read()
with open(filename, 'w') as f:
    s = re.sub(y, z, s)
    f.write(s)
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming your txt save in src.txt:

morning
night
sun
moon

In windows,you can use this batch script,save in replace.bat:

@echo off
setlocal enabledelayedexpansion
set filename=%1
set oldstr=%2
set newstr=%3

for /f "usebackq" %%i in (%filename%) do (
    set str=%%i
    set replace=!str:%oldstr%=%newstr%!
    echo !replace!
)

Useage:

replace.bat src.txt morning afternoon > newsrc.txt

or grepWin.

Use sed or gawk may be more simple.

sed -i "s/morning/afternoon/g" src.txt

Comments

-1

Perhaps you are looking for the Python replace() method?

str = file.readlines()
str = str.replace(y, z) #this will replace substring y with z within the parent String str

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.