似乎vehicles.write(cars_file)
和vehicles = cars_Etree.parse(cars_file)
的文件名出现问题:
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)
错误:
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文件位于同一项目文件夹中。我尝试使用文件名提供路径,但仍然无效。
<?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>
答案 0 :(得分:0)
现在工作正常但我仍在改进它。谢谢
我在main.py中做了这个修改:
path = "/Users/benbitdiddle/PycharmProjects/VehicleFilter/"
CF = CarFilter(path+args.file_name, args.car_make)
CF.filterCar()
并改变了&#39; w&#39; wb&#39;在CarFilter.py类文件中:
with open(self.file_name, 'wb') as car_file:
self.vehicles.write(car_file)