I’m trying to create a json file in below format. However, I’m unable to remove the last comma just before "]"
fl = open('fri.txt', 'r')
fw = open('test.txt', 'w')
lines=fl.readlines()
lines = [x.strip() for x in lines]
#print(lines)
#print(type(lines))
month = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
fw.write(str.upper('"%3s": [ n' % month[11]))
for row in lines:
if row.find("-12-") != -1:
#fw.write('string exists in file')
#fw.write('line Number:', lines.index(row))
fw.write(str(' "%2s",' % lines[lines.index(row)][-2:] + "n"))
fw.write("],n")
fl.close
Output: test.txt
"DEC": [
"06",
"13",
"20",
"27",
],
Expected output:
"DEC": [
"06",
"13",
"20",
"27"
],
I need to remove the last comma ‘"27",’ here. I tried to use b.But, its not working. Kindly assist to achieve this in a better way. Similar blocks will be created for other months too. So, It has to be done in each of those blocks.
tried using backspace character. But, its not working.
2
Answers
Since you’re dealing with strings, using backspace
(b)
won’t work because it only moves the cursor back without actually removing characters from the string.You can achieve this by using
str.join()
method to join the list items with commas and it prevents the unwanted comma from appearing.Here is the adjusted code:
Now the Output looks like this:
Greetings DF
Unless you are not really using JSON but just something similar, I would strongly suggest using the builtin
json
module. Also, you mentioned that you’d repeat that block for the other months, but you can just use a loop for that. I am not sure how exactly your input looks, but I’d suggest trying something like this:(Minor changes: iterating the lines without storing them all in a list, using
in
instead offind
, usingwith
to open and close files, and not needlessly usingindex
.)Alternatively, you may also store the lines in a list and then use a nested dict- and list-comprehension, which may or may not be considered more readable: