2016-12-03 92 views
1

我用随机数替换2010年所有出现在我的JSON文件1990年和2020年Python的类型错误:预期字符串或其他字符缓冲区对象

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()) 

之间我得到这个错误:

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

这里是这种情况发生的一个例子:

"myDate" : "2010_02", 
+0

是否有您的JSON文件的一些空行? – ettanany

+0

@ettanany没有黑线!每一行至少有一个字符。 – cplus

+0

@Mpondomise尝试我的解决方案 – eyllanesc

回答

1

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.

新值必须是字符串,但是您传递的是int类型的值。

变化:

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

到:

line.replace('2010', str(randint(1990, 2020))).rstrip() 
相关问题