Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file in python and get value odoo 9

How in below example get NUM or CODE

lines = filename.split('\n')
    for line in lines:
        print("CODE is:" + ???);
        #CODE is: 1111
        #CODE is: 2222
        #CODE is: 3333

file

<FROM ID="1610350010160016">
      <PR NUM="1" CODE="1111" />
      <PR NUM="2" CODE="2222" />
      <PR NUM="3" CODE="3333" />
    </FROM>

How get NUM and CODE from abowe example?

like image 261
Pointer Avatar asked Jun 04 '26 21:06

Pointer


2 Answers

This is one way using regex:

import re
lines = filename.split('\n')
    for line in lines:
        print('NUM is : {}'.format(''.join(re.findall(r'NUM="(\w+)', line))), end=" ")
        print('CODE is : {}'.format(''.join(re.findall(r'CODE="(\w+)', line))))

'''
NUM is : 1  CODE is : 1111
NUM is : 2  CODE is : 2222
NUM is : 3  CODE is : 3333
'''
like image 191
Austin Avatar answered Jun 07 '26 11:06

Austin


You can use the standard library (Python 2.5+):

import xml.etree.ElementTree as ET

for element in ET.parse('data.xml').getroot():
    print(element.attrib['NUM'], element.attrib['CODE'])

where data.xml contains the XML data.

If you have the data in a string, you can use the string parser instead:

ET.fromstring('Your XML data')

This solution doesn't use regex and is very compact and readable, and it works with any data type (for example, dates in the format 'gg.mm.aaaa').

like image 21
Daniele Murer Avatar answered Jun 07 '26 10:06

Daniele Murer