简体   繁体   中英

How to remove a particular character from a txt file?

Have a txt with contents :

 {
 hello : 1,two:three,four:five,six:seven,
 }

how to remove the last , in the above string ?

while using them as dictionaries for further. it cant be parsed because of the last delimiter.

code :

import json
d2=json.load(open(test.txt))

i cant change the source code. coz i am extracting data from a json file(json.dump) and creating a new json. is there any way of doing that other than dump/changing the source code

This removes the last , in your string without the need of any further import 's.

with open('test.txt', 'r') as f:
   s = f.read()
s = s[::-1].replace(',', '', 1)[::-1]

the output of s is then:

{
 hello : 1,two:three,four:five,six:seven
}

Simple replace should work fine.

broken_json = '''{
  hello : 1,two:three,four:five,six:seven,
  bye : 42,ick:poo,zoo:bar,}'''
j = broken_json.replace(',}', '}').replace(',\n}','\n}')

The result at this point is still not valid JSON, because the dictionary keys need to be quoted; but this is outside the scope of your question so I will not try to tackle that part.

string ='{hello : 1,two:three,four:five,six:seven,}'
length = len(string)

for i in range(length):
   if(string[i] == ','):
      string2 = string[0:i] + string[i + 1:length]
print (string2)

The output type would be a string. So, convert it to a dict later.

import re
string ='{hello : 1,two:three,four:five,six:seven,}'
match = re.search(r'(.*),[^,]*$', string)
print (match.group(1)+"}")

Try this @selcuk for an efficient one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM