Reputation: 1035
I'm reading from dataset with json objects, in dataset some of values has abcd\nabdc format. I used following code:
for line in open("c:\\dataset","r+").readlines():
d= json.loads(line)
str1 = d['strkey1']
str1.replace('\n' , '')
but it fails to replace.
Upvotes: 0
Views: 973
Reputation: 133554
d['strkey1'] = d['strkey1'].replace('\n', '')
Strings are immutable, so string methods return new strings, not modifying the original.
Also:
for line in open("c:\\dataset","r+"):
Will suffice, you don't need to .readlines()
the whole file into memory before going through each line. But that still isn't enough, you need to remember to close your files, a with
statement will handle that for you:
with open("c:\\dataset","r+") as f:
for line in f:
# do stuff
Upvotes: 4
Reputation: 19416
Just change your code to:
for line in open("c:\\dataset","r+").readlines():
dict = json.loads(line)
dict['strkey1'] = dict['strkey1'].replace('\n','')
This works and your's doesn't as strings are immutable (they can't be changed), so string methods return a new string, (which here you need to store)
Upvotes: 1