Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

csv data ending with comma at end | python |

I have written a code but the issue with the code is

I am not able to identify how to get rid of last ending command comma from my obtained expected output

Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import xml.etree.ElementTree as ET

xml_data='''
<job_details>
    <role>
        <name>Vikas</name>
        <salary>$5.95</salary>
        <job_description>Developer</job_description>
    </role>
    <role>
        <name>Dip</name>
        <salary>$7.95</salary>
        <job_description>Backend Developer</job_description>
    </role>
</job_details>
'''

get_root_element = ET.fromstring(xml_data)
cnt=0
for i in range(len(list(get_root_element))):
  for x in get_root_element[i]:
    print(x.text,end=",")
    cnt=cnt + 1
    if cnt == len(list(get_root_element[1])):
      break
  print()

Expected output :

Vikas,$5.95,Developer,
Dip,$7.95,Backend Developer,

>Solution :

You can simplify your code with this:

You can iterate directly through get_root_Elements.
Then instead of using print() you take all elements of each item and join it with the right seperator.
Also no need to break out of the for loop, it will stop itself.
I appended all results to a list out, where you have 2 strings seperated by ,

import xml.etree.ElementTree as ET

xml_data='''
<job_details>
    <role>
        <name>Vikas</name>
        <salary>$5.95</salary>
        <job_description>Developer</job_description>
    </role>
    <role>
        <name>Dip</name>
        <salary>$7.95</salary>
        <job_description>Backend Developer</job_description>
    </role>
</job_details>
'''

get_root_element = ET.fromstring(xml_data)

out = []
for item in get_root_element:
    res = ','.join(x.text for x in item)
    out.append(res)

print(out) 
['Vikas,$5.95,Developer', 'Dip,$7.95,Backend Developer']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading