csv data ending with comma at end | python |

Advertisements

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:

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']

Leave a ReplyCancel reply