【问题标题】:How to create csv file after xml parsing using python如何使用python解析xml后创建csv文件
【发布时间】:2018-11-27 14:57:21
【问题描述】:

我是 python 的新手,我已经能够解析我的 xml 文件并得到我所期望的,这是我在 shell 上得到的一些输出:

 * p84182 [Goalkeeper] 16 - total_through_ball = [1]
 * p84182 [Goalkeeper] 16 - duel_lost = [4]
 * p84182 [Goalkeeper] 16 - blocked_scoring_att = [1]
 * p84182 [Goalkeeper] 16 - leftside_pass = [46]
 * p84182 [Goalkeeper] 16 - dispossessed = [1]
 * p84182 [Goalkeeper] 16 - accurate_cross = [2]
 * p84182 [Goalkeeper] 16 - att_rf_total = [1]

我想将其转换为包含这 5 列的 csv 文件,但每次运行代码时都会遇到相同的错误:

Traceback (most recent call last):
  File "C:\Users\Hp\Documents\test4.py", line 20, in <module>
    print.fichier(ID,Position,Shirt,Types,Reponse)
AttributeError: 'builtin_function_or_method' object has no attribute 'fichier'

这是我的python代码:

import os
from xml.etree import ElementTree
import csv

file_name="C:/Users/Hp/Desktop/BYG/PSG-Amiens.xml"
full_file=os.path.abspath(os.path.join('BYG',file_name))
dom=ElementTree.parse(full_file)

fichier=open('data.csv','w')

Stats=dom.findall('SoccerDocument/MatchData/TeamData/PlayerLineUp/MatchPlayer')

Type=dom.findall('SoccerDocument/MatchData/TeamData/PlayerLineUp/MatchPlayer[@PlayerRef="p15780"]/Stat')
for s in Stats:
    ID=s.get('PlayerRef')
    Position=s.get('Position')
    Shirt=s.get('ShirtNumber')
    for t in Type:
            Types=t.get('Type')
            Reponse=t.text
            print.fichier(ID,Position,Shirt,Types,Reponse)

fichier.close()

如何解决这个问题?并将我的 xml 解析转换为 csvfile?

【问题讨论】:

  • 是不是 : print.fichier 抛出了你的错误?
  • 这就是为什么您总是必须在您的问题中提供整个回溯。它提供了更多信息,而不仅仅是文字错误文本。
  • @MatinaG 感谢您的回答,我更新了我的问题,是的,是 print.fichier 引发了您的错误

标签: python xml csv


【解决方案1】:

print.fichier 无效。要打印到文件,请使用print(ID,Position,Shirt,Types,Response,file=fichier),但这也不会给您.csv。请参阅csv 模块。编写 CSV 的基础是:

import csv
with open('data.csv','w',newline='') as f:
    w = csv.writer(f)
    w.writerow([ID,Position,Shirt,Types,Response])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    相关资源
    最近更新 更多