0

I am replacing the '2010' with a random number:

from random import randint
with open("data.json", "rt") as fin:
    with open("dataout.json", "wt") as fout:
        for line in fin:
            fout.write(line.replace('2010', str(randint(1990, 2007))))

how can I replace two items in one code, that is:

fout.write(line.replace('2099', str(randint(1800, 1900))))
fout.write(line.replace('2010', str(randint(1990, 2007))))
2
  • 1
    So one line contains both 2099 and 2010 and you would like to replace both in one go instead of calling the function twice? Commented Dec 3, 2016 at 13:49
  • no they will occur on different lines. Commented Dec 3, 2016 at 13:57

2 Answers 2

2

You just need to use if to check if your line contains '2099' or '2010' like this:

from random import randint

with open("data.json", "rt") as fin:
    with open("dataout.json", "wt") as fout:
        for line in fin:
            if '2010' in line:
                fout.write(line.replace('2010', str(randint(1990, 2007))))
            if '2099' in line:
                fout.write(line.replace('2099', str(randint(1800, 1900))))
Sign up to request clarification or add additional context in comments.

Comments

1

Use two replace() method:

from random import randint
with open("data.json", "rt") as fin:
    with open("dataout.json", "wt") as fout:
        for line in fin:
            fout.write(line.replace('2010', str(randint(1990, 2007))).replace('2099', str(randint(1800, 1900))))

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.