5

I am replacing all the occurrences of 2010 in my JSON file with a random number between 1990 and 2020.

import fileinput
from random import randint
f = fileinput.FileInput('data.json', inplace=True, backup='.bak')
for line in f:
    print(line.replace('2010', randint(1990, 2020)).rstrip())

I get this error:

Traceback (most recent call last): File "replace.py", line 5, in print(line.replace('2010', randint(1990, 2020)).rstrip()) TypeError: expected a string or other character buffer object

And here is one example of such an occurrence:

"myDate" : "2010_02",
3
  • Is there some blank line in your json file? Commented Dec 3, 2016 at 13:14
  • @ettanany no black line! every line has at least one character. Commented Dec 3, 2016 at 13:15
  • @Mpondomise try with my solution Commented Dec 3, 2016 at 14:00

1 Answer 1

4

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

The new value must be string, but you are passing a value of type int.

change :

line.replace('2010', randint(1990, 2020)).rstrip())

to:

line.replace('2010', str(randint(1990, 2020))).rstrip()
Sign up to request clarification or add additional context in comments.

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.