简体   繁体   English

在CSV中将CSV数据传输到不同的函数中

[英]Transferring CSV data into different Functions in Python

i need some help. 我需要协助。 Basically, i have to create a function to read a csv file then i have to transfer this data into another function to use the data to generate a xml file. 基本上,我必须创建一个函数来读取csv文件,然后我必须将此数据传输到另一个函数,以使用该数据生成一个xml文件。 Here is my code: 这是我的代码:

import csv
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
from xml.etree.ElementTree import ElementTree
import xml.etree.ElementTree as etree

def read_csv():
    with open ('1250_12.csv', 'r') as data:
         reader = csv.reader(data)
    return reader

def generate_xml(reader):
    root = Element('Solution')
    root.set('version','1.0')
    tree = ElementTree(root)

    head = SubElement(root, 'DrillHoles')
    head.set('total_holes', '238')

    description = SubElement(head,'description')
    current_group = None
    i = 0
    for row in reader:
        if i > 0:
           x1,y1,z1,x2,y2,z2,cost = row
           if current_group is None or i != current_group.text:
                current_group = SubElement(description, 'hole',{'hole_id':"%s"%i})

                information = SubElement (current_group, 'hole',{'collar':', '.join((x1,y1,z1)),
                                                   'toe':', '.join((x2,y2,z2)),
                                                   'cost':    cost})
        i+=1

def main():
    reader = read_csv()
    generate_xml(reader)

if __name__=='__main__':
   main()

but i get an error when i try to pass reader, the error is: ValueError: I/O operation on closed file 但是当我尝试传递阅读器时出现错误,错误是:ValueError:关闭文件的I / O操作

Turning the reader into a list should work: 将阅读器变为列表应该有效:

def read_csv():
      with open ('1250_12.csv', 'r') as data:
           return list(csv.reader(data))

You tried to read from a closed file. 您试图从已关闭的文件中读取。 list will trigger the reader to read the whole file. list将触发读者读取整个文件。

the with statement tells python to clean up the context manager (in this case, a file) once control exits its body. with语句告诉python在控件退出其主体后清理上下文管理器(在本例中为文件)。 Since functions exit when they return, there's no way to get data out of it with the file still open. 由于函数在返回时退出,因此在文件仍处于打开状态时无法从中获取数据。

Other answers suggest reading the whole thing into a list, and returning that; 其他答案建议将整个内容读入列表,然后返回; this works, but may be awkward if the file is very large. 这可行,但如果文件非常大,可能会很尴尬。

Fortunately, we can use generators: 幸运的是,我们可以使用生成器:

def read_csv():
    with open('1250_12.csv', 'r') as data:
        reader = csv.reader(data)
        for row in reader:
            yield row

Since we yield from inside the with , we don't have to clean up the file before getting some rows. 因为我们从with内部产生,所以在获取一些行之前我们不必清理文件。 Once the data is consumed, (or if the generator is itself cleaned up,) the file will be closed. 一旦数据被消耗,(或者如果生成器本身被清除),文件将被关闭。

So when you read a csv file it is very important to put that file into a list. 因此,当您阅读csv文件时,将该文件放入列表中非常重要。 This is because most operations you cannot perform on the csv.reader file, and that if you do, once you loop through it and it is at the end of the file, you can no longer do anything with it unless you open it and read it again. 这是因为你无法在csv.reader文件上执行的大多数操作,如果你这样做,一旦你遍历它并且它在文件的末尾,除非你打开并阅读它,否则你不能再用它做任何事情了。它再次。 So lets just change your read_csv function 所以我们只需更改read_csv函数即可

def read_csv():
    with open ('1250_12.csv', 'r') as data:
         reader = csv.reader(data)
         x = [row for row in reader]
    return x

Now you are manipulating a list and everything should work perfectly! 现在你正在操纵一个列表,一切都应该完美!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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