skip to Main Content

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


  1. 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:

    fl = open('fri.txt', 'r')
    fw = open('test.txt', 'w')
    
    lines = fl.readlines()
    lines = [x.strip() for x in lines]
    
    month = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
    
    fw.write(str.upper('"%3s": [ n' % month[11]))
    
    items = []
    for row in lines:
        if row.find("-12-") != -1:
            items.append('"%2s"' % lines[lines.index(row)][-2:])
    
    fw.write(",n".join(items) + "n")
    fw.write("],n")
    
    fl.close()
    fw.close()
    

    Now the Output looks like this:

    "DEC": [ 
    "06", 
    "13", 
    "20", 
    "27"
    ],
    

    Greetings DF

    Login or Signup to reply.
  2. 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:

    import json
    
    months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']    
    with open('fri.txt', 'r') as fl:
        res = {m: [] for m in months}
        for line in fl:
            for i, m in enumerate(months, start=1):
                if f"-{i:02}-" in line:
                    res[m].append(line.strip()[-2:])
    
    with open('test.txt', 'w') as fw:
        json.dump(res, fw, indent=2)
    

    (Minor changes: iterating the lines without storing them all in a list, using in instead of find, using with to open and close files, and not needlessly using index.)

    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:

    with open('fri.txt', 'r') as fl:
        lines = [line.strip() for line in fl]
        res = {
            m: [line[-2:] for line in lines if f"-{i:02}-" in line]
            for i, m in enumerate(months, start=1)
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search