0
XMLファイルをディレクトリ内で1つずつ処理しようとしています。基本的に値を読み取り、CSVファイルを入力します。私は各XMLを1つずつ解析するのに問題があります。私のコードの問題は、csvWriter.writerowはディレクトリ内の最後のXMLファイルからの値だけを書き込むことです。 ElementTree.parse(path)のルートにあるすべての項目に対してループがあります。私はディレクトリに各XMLファイルの各行を記述したい。os.path.joinを使用して変数をループする
from lxml import etree as ElementTree
import csv
import os
import errno
import shutil
def writeData(item):
csvFile = open('D:\\metadata.csv', 'w', newline='')
csvWriter = csv.writer(csvFile, delimiter='|',
lineterminator='\n')
csvWriter.writerow([
'type',
'object',
'title',
'subject',
'domain',
'name',
'_name',
'version_label',
'creator_name',
'creation_date',
'modifier',
'modify_date',
'content_type',
'chronicle_id',
'antecedent_id',
'activity_date',
'search_from_date',
'number',
'service_code',
'initial_inspection_date',
'search_to_date',
'File Name',
'Location',
])
csvWriter.writerow([
root[0][0].text,
root[0][1].text,
root[0][2].text,
root[0][3].text,
root[0][4].text,
root[0][5].text,
root[0][6].text,
root[0][7].text,
root[0][8].text,
root[0][9].text,
root[0][10].text,
root[0][11].text,
root[0][12].text,
root[0][13].text,
root[0][14].text,
root[0][15].text,
root[0][16].text,
root[0][17].text,
root[0][18].text,
root[0][19].text,
root[0][20].text,
root[2].text,
root[1].text,
])
csvFile.close()
for file in os.listdir('D:\\temp\\Export\\test'):
if file.endswith('.xml'):
path = os.path.join('D:\\temp\\Export\\test', file)
tree = ElementTree.parse(path)
#print(tree)
root = tree.getroot()
#print(root)
for item in root:
print(item)
writeData(item)
おかげけど...取得エラートレースバック(最新の呼び出しの最後): を代わりに一度だけ、それを開いて、このようなあなたの 書き込みデータ(csv_writer、項目) ファイル "extractMetadata.py"、ライン11に、書き込みデータ にcsvWriter.writerow([ NameError:名前は 'csvWriter' –
user1457821
writeData
関数に渡してみてください、反復を書くすべてのための.csvファイルを再オープンします"extractMetadata.py"、ライン70をファイルWoopsに定義されていません私の悪い、私は 'csv_writer'を' csv_writer'に改名し、明らかに変数を忘れてしまった。私は答えを編集した。 –
われわれは2番目のループ "for root in item:"データを複製する必要はありません。ヘッダー行を1回だけ作成することは知っていますか? – user1457821