0

My Problem is the following

I have one file, it contains more than 1000 rows, i am getting expected output , problem is some lines get skipped not appended to output file.i have tried but failed to found the issue

def grouping():
global date,os
try:
    output = []
    temp = []
    currIdLine = ""
    with( open ('usergroups.csv', 'r')) as f:
        for lines in f.readlines():
            line = lines.strip()
            if not line:
                continue
            if line.startswith('uuid'):
                output.append(line)
                continue
            if line.startswith('id:'):
                if temp:
                    #print(temp)
                    output.append(currIdLine + ";" + ','.join(temp)) 
                    temp.clear()
                currIdLine = line
            else:
                temp.append(line)
    output.append(currIdLine + ";" + ','.join(temp))
    with open('usergroup.csv', 'w') as f1:
        for row in output:
            f1.write(row + '\n')
    print("Emails appended to Previous line")        
    CSV = 'usergroups.csv'
    if(os.path.exists(CSV) and os.path.isfile(CSV)):
        os.remove(CSV)
          
except:
    print("Emails appended - Failed")        

my sample source file:

uuid;UserGroup;Name;Description;Owner;Visibility;Members  ----> header
id:;group1;raji;xyzabc;ramya;public;
abc
def
geh
id:;group2;ram;xyzabc;mitu;public; ---> This line not appended to output file
id:;group3;ram;xyzabc;mitu;public; ---> This line not appended to output file
id:;group4;raji;rtyui;ramya;private
cvb
nmh
poi

output of the above code

uuid;UserGroup;Name;Description;Owner;Visibility;Members  ----> header of the file
id:;group1;raji;xyzabc;ramya;public;abcdefgeh
id:;group4;raji;rtyui;ramya;private

my desired output:

uuid;UserGroup;Name;Description;Owner;Visibility;Members  ----> header of the file
id:;group1;raji;xyzabc;ramya;public;abcdefgeh
id:;group2;ram;xyzabc;mitu;public;
id:;group3;ram;xyzabc;mitu;public;
id:;group4;raji;rtyui;ramya;private
Mittu BR
  • 23
  • 4
  • 2
    I think it should be easy to spot the mistake if you use a debugger and go through the code line by line. Also, as a side note, I'd advise you [not to use `global`](https://stackoverflow.com/a/19158418/1185254). – alex Jan 25 '23 at 10:18
  • @alex i have tried , but could not able to find – Mittu BR Jan 25 '23 at 12:00
  • have a close look at your temp variable Raji – gimba Jan 25 '23 at 12:42
  • 2
    Maybe try the `csv` module instead of attempting to write a csv parser yourself – l4mpi Jan 25 '23 at 12:46

1 Answers1

0

finally found the mistake. mentioned my mistake here

                if temp:
                #print(temp)
                output.append(currIdLine + ";" + ','.join(temp))
                temp.clear()
                **else: # <-- this block is needed**
                output.append(currIdLine)
          
Mittu BR
  • 23
  • 4