简体   繁体   中英

elementTree is not opening and parsing my xml file

seems like vehicles.write(cars_file) and vehicles = cars_Etree.parse(cars_file) are having a problem with the file name:

import argparse
import xml.etree.ElementTree as cars_Etree

# elementTree not reading xml file properly

if __name__ == '__main__':

    parser = argparse.ArgumentParser()

    parser.add_argument(
        dest='file_name',
        action='store',
        help='File name',
        metavar='FILE'
    )
    parser.add_argument(
        'car_make', help='car name')

    args = parser.parse_args()

    with open(args.file_name, 'r') as cars_file:
        vehicles = cars_Etree.parse(cars_file)
        cars = vehicles.getroot()

        for make in cars.findall(args.car_make):
            name = make.get('name')
            if name != args.car_make:
                cars.remove(make)

        with open(args.file_name, 'w') as cars_file:
            vehicles.write(cars_file)

Error:

Traceback (most recent call last):
  File "/Users/benbitdiddle/PycharmProjects/VehicleFilter/FilterTest.py", line 23, in <module>
    vehicles = cars_Etree.parse(cars_file)
  File "/Applications/anaconda/lib/python3.5/xml/etree/ElementTree.py", line 1184, in parse
    tree.parse(source, parser)
  File "/Applications/anaconda/lib/python3.5/xml/etree/ElementTree.py", line 596, in parse
    self._root = parser._parse_whole(source)
xml.etree.ElementTree.ParseError: syntax error: line 1, column 0

XML file, which I am trying to filter, is in the same project folder. I tried supplying the path with the file name and it still didn't work.

<?xml version="1.0" encoding="UTF-8"?>
<cars>
    <make name="toyota">
        <model name="tacoma" />
        <model name="tundra" />
    </make>
    <make name="ford">
        <model name="escort" />
        <model name="taurus" />
    </make>
    <make name="chevy">
        <model name="silverado" />
        <model name="volt" />
    </make>
</cars>

works fine now but im still improving it. thank you

I made this modification in main.py:

path = "/Users/benbitdiddle/PycharmProjects/VehicleFilter/"
CF = CarFilter(path+args.file_name, args.car_make)
CF.filterCar()

And changed 'w' to wb' in CarFilter.py class file:

    with open(self.file_name, 'wb') as car_file:
        self.vehicles.write(car_file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM