Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 只有部分数据被写入cvs文件,其余数据丢失_Python_Csv_Xml Parsing - Fatal编程技术网

Python 只有部分数据被写入cvs文件,其余数据丢失

Python 只有部分数据被写入cvs文件,其余数据丢失,python,csv,xml-parsing,Python,Csv,Xml Parsing,我正在解析许多xml文件,并将某些信息放入csv文件中。因为我的xml文件名为:“1.xml”、“2.xml”等等。。。我使用for循环遍历不同的Xml文件标题。但是,根据我在for循环中使用的范围,我的csv文件包含不同的数据。例如,当我的For循环范围为1:200时,我的csv文件包含从xml文件1到199的信息。但是,当我将范围更改为1:300时,我的csv文件只包含xml文件217到249的信息。实际存储在csv文件中的信息会根据我输入的for循环范围而变化。还有其他人犯过这个错误吗?你

我正在解析许多xml文件,并将某些信息放入csv文件中。因为我的xml文件名为:“1.xml”、“2.xml”等等。。。我使用for循环遍历不同的Xml文件标题。但是,根据我在for循环中使用的范围,我的csv文件包含不同的数据。例如,当我的For循环范围为1:200时,我的csv文件包含从xml文件1到199的信息。但是,当我将范围更改为1:300时,我的csv文件只包含xml文件217到249的信息。实际存储在csv文件中的信息会根据我输入的for循环范围而变化。还有其他人犯过这个错误吗?你有什么解决办法吗

我的代码如下:

import xml.etree.ElementTree as ET
import csv
from pathlib import Path

# open a file for writing

data_labels = open('DataLabels.csv', 'w', newline='')
missing_files = open('MissingFiles.csv', 'w', newline = '')

# create the csv writer object
csvwriter = csv.writer(data_labels)
csvwriter2 = csv.writer(missing_files)
data_head = []
data = []
missingfiles = 0
missfiles = []

MediaId = "Media Id"
    #data_head.append (MediaId)

Family = "Family"
    #data_head.append (Family)

Species = "Species"
    #data_head.append (Species)

Genus = "Genus"
Content = "Content"
ClassId = "ClassId"
    #data_head.append (Genus)

data_head.append(MediaId)
    #   Family = member.find('Family').tag
data_head.append(Content)
data_head.append(ClassId)
data_head.append(Family)
    #   Species = member.find('Species').tag
data_head.append(Species)
    #   Genus = member.find('Genus').tag
data_head.append(Genus)

csvwriter.writerow(data_head)

for i in range (1, 190):
    #print (i)
    data = []

    inputfilename = str(i)+ ".xml"

    my_file = Path(inputfilename)
    if my_file.is_file():

        data_labels = open('DataLabels.csv', 'w', newline='')

        tree = ET.parse(inputfilename)
        root = tree.getroot()

        MediaId = root [2].text
        Content = root[4].text
        ClassId = root[5].text
        Family = root[6].text
        Species = root[7].text
        Genus = root[8].text

        #print (vote)
        #count = 0
        #for Image in root.find('MediaId'):
        #print (child.tag, child.attrib)
        #name = child.find('MediaId').text
    #   print (Image.find ('MediaId').text)
    ##csvwriter.writerow (data_head)

    #data = []

    #if count == 0:
    #   print ("count is zero i'm in loop")
    #   MediaId = member.find('MediaId').tag

    #   count = count + 1
    #else:
    #MediaId = root.findall('MediaId').text
        data.append(MediaId)
        data.append (Content)
        data.append (ClassId)
#Family = member.find('Family').text
        data.append(Family)
#Species = member.find('Species').text
        data.append(Species)
#Genus = member.find('Genus').text
        data.append(Genus)
        csvwriter.writerow(data)
        data_labels.close()
        #print (data)
    else:
        missingfiles = missingfiles +1
        missfiles = []
        missfiles.append(inputfilename)
        csvwriter2.writerow(missfiles)


print ("missing", missingfiles, "files")
data_labels.close()
missing_files.close()

print ("done")

在附加模式下打开csv,否则将覆盖同一个文件。

在附加模式下打开csv,否则将覆盖同一个文件。

我认为您需要将脚本划分为小的可读函数

首先,您可以创建一个函数来解析XML文件:

import xml.etree.ElementTree as ET


def parse_xml_file(xml_path):
    """ Parse an XML file and return the data. """
    # type: (str) -> list
    tree = ET.parse(xml_path)
    root = tree.getroot()
    return [
        root[2].text,
        root[4].text,
        root[5].text,
        root[6].text,
        root[7].text,
        root[8].text]
此函数用于解析XML文件并返回一条包含值列表的记录

然后,您可以创建一个函数来迭代XML文件(现有文件)列表,然后填充CSV文件:

import csv
import io
import os


def populate_data_labels(xml_path_list, work_dir="."):
    header = ["Media Id", "Family", "Species", "Genus", "Content", "ClassId"]
    with io.open(os.path.join(work_dir, 'DataLabels.csv'), 'w') as fd:
        writer = csv.writer(fd)
        writer.writerow(header)
        for xml_path in xml_path_list:
            writer.writerow(parse_xml_file(xml_path))
此函数使用
parse_xml_file()
提取每条记录

您可以创建一个函数来记录丢失的文件。您可以使用CSV格式(或简单文本文件):

最后,您可以编写一个函数来搜索XML文件并调用前面的函数:

def parse_work_dir(work_dir="."):
    all_files = [os.path.join(work_dir, "{0}.xml".format(idx))
                 for idx in range(1, 190)]
    existing_files = (path for path in all_files if os.path.exists(path))
    populate_data_labels(existing_files, work_dir)
    missing_files = (path for path in all_files if not os.path.exists(path))
    populate_missing_files(missing_files, work_dir)
用法:

parse_work_dir("/path/to/your/working/dir")

我认为您需要将脚本划分为小的可读函数

首先,您可以创建一个函数来解析XML文件:

import xml.etree.ElementTree as ET


def parse_xml_file(xml_path):
    """ Parse an XML file and return the data. """
    # type: (str) -> list
    tree = ET.parse(xml_path)
    root = tree.getroot()
    return [
        root[2].text,
        root[4].text,
        root[5].text,
        root[6].text,
        root[7].text,
        root[8].text]
此函数用于解析XML文件并返回一条包含值列表的记录

然后,您可以创建一个函数来迭代XML文件(现有文件)列表,然后填充CSV文件:

import csv
import io
import os


def populate_data_labels(xml_path_list, work_dir="."):
    header = ["Media Id", "Family", "Species", "Genus", "Content", "ClassId"]
    with io.open(os.path.join(work_dir, 'DataLabels.csv'), 'w') as fd:
        writer = csv.writer(fd)
        writer.writerow(header)
        for xml_path in xml_path_list:
            writer.writerow(parse_xml_file(xml_path))
此函数使用
parse_xml_file()
提取每条记录

您可以创建一个函数来记录丢失的文件。您可以使用CSV格式(或简单文本文件):

最后,您可以编写一个函数来搜索XML文件并调用前面的函数:

def parse_work_dir(work_dir="."):
    all_files = [os.path.join(work_dir, "{0}.xml".format(idx))
                 for idx in range(1, 190)]
    existing_files = (path for path in all_files if os.path.exists(path))
    populate_data_labels(existing_files, work_dir)
    missing_files = (path for path in all_files if not os.path.exists(path))
    populate_missing_files(missing_files, work_dir)
用法:

parse_work_dir("/path/to/your/working/dir")

哪个操作系统?我看不出你是怎么得到任何数据的。
for
循环中的
data\u labels=open('DataLabels.csv','w',newline='')
会一直覆盖文件。在linux上,它将取消您正在向其写入数据的原始文件的链接。在windows上,这不是共享冲突吗?(我没有一台机器来测试那台…)哪个操作系统?我看不出你是怎么得到任何数据的。
for
循环中的
data\u labels=open('DataLabels.csv','w',newline='')
会一直覆盖文件。在linux上,它将取消您正在向其写入数据的原始文件的链接。在windows上,这不是共享冲突吗?(我没有机器来测试那台…)非常感谢!成功了!非常感谢你!成功了!我认为你是绝对正确的,我应该把我的代码分成更小的部分,但考虑到我对编码的新认识,将代码分成几部分(我在编写代码时进行了测试)然后创建和调用函数就更容易了。非常感谢您重组我的代码!我认为你是绝对正确的,我应该把我的代码分成更小的部分,但考虑到我对编码的新认识,将代码分成几部分(我在编写代码时进行了测试)然后创建和调用函数就更容易了。非常感谢您重组我的代码!