I am writing a script that will replace the word in the file with a user input. Script:

print "enter your text" newText = input("#") with open('test.txt', 'r') as f: old_data = f.read() new_data = old_data.replace('oldtext', (newText)) with open('test.txt', 'w') as f: f.write(new_data) 

What's my mistake?

Closed due to the fact that the participants are not on topic: Sergey Gornostaev , aleksandr barakin , 0xdb , entithat , user192664 4 Nov '18 at 17:16 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - Sergey Gornostaev, aleksandr barakin, 0xdb, entithat, Community Spirit
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • What is the problem? What error message is displayed? - Alexshev92
  • TypeError: expected a string after another character buffer object after I enter any digit - user314586
  • Perhaps you should remove the parentheses: new_data = old_data.replace('oldtext', newText) - Alexshev92
  • I tried but the same error - user314586
  • one
    Interesting .. try newText = raw_input("#") . In python2 input is eval(raw_input(prompt)) , so the result will be interpreted depending on the input, and in newText should be a line - gil9red

1 answer 1

Replace:

 newText = input("#") 

on:

 newText = raw_input("#") 

The reason is that input (prompt) is actually executed as eval(raw_input(prompt)) , because of this you can get not a string, but a different type