繁体   English   中英

如何在python中处理大型csv文件?

[英]How to deal with large csv file in python?

我有一个包含40k行数据的CSV文件。

我的每个函数都打开csv文件并使用它,然后关闭它。 有没有一种方法可以打开一次文件然后将其关闭,并且可以随时使用它? 我试图将每个字段放在一个单独的列表中,并在每次调用它或在字典中使用它,但是如果这两种方法都需要花很长时间来处理,那么这两种方法都可以工作到1k行,我发现了一种通过过滤来加快速度的方法他们,但不确定如何应用。

我的代码示例。

files=open("myfile.csv","r")


def spec_total():
    total = 0.0
    files.readline() # skip first row
    for line in files:
        field=line.strip().split(",")  #make Into fields
        tall=float(field[0])      
            if tall >= 9.956:
        total +=tall
    print("The sum is: %0.5f" % (total))

spec_total()
files.close()

其他功能

files=open("3124749c.csv","r")
def code():
    match= 0
    files.readline() # skip first row
    for row in files:
        field=row.strip().split(",") #make Into fields
        code=(field[4])
        import re
        if re.search(r'\[[A-Za-z][0-9]+\][0-9]+[A-Za-z]{2}[0-9]+#[0-9]+', code) is None:
            match += 1
    print("The answer that do not match code is :",match)

code()

files.close()

每次打开csv文件并将其拆分为多个字段时,还有很多功能可以打开,以便识别我要引用的字段。

如果我正确理解,请尝试:

import csv
total = 0.0
for row in csv.reader(open("myfile.csv")):
    tall = float(row[0])
    if tall >= 9.956:
        total += tall

print("The sum is: %0.5f" % total)

更复杂的版本-创建用于处理每一行的计算类。

class Calc(object):
    def process(self,row):
       pass
    def value(self):
        pass

class SumColumn(Calc):
    def __init__(self, column=0,tall=9.956):
        self.column = column
        self.total = 0

    def process(self, row):
        tall = float(row[0])
        if tall >= self.tall:
           self.total += tall

    def value(self):
        return self.total

class ColumnAdder(Calc):
    def __init__(self, col1, col2):
        self.total = 0
        self.col1 = col1
        self.col2 = col2

    def process(self, row):
        self.total += (row[self.col1] + row[self.col2])

    def value(self):
        return self.total

class ColumnMatcher(Calc):
   def __init__(self, col=4):
      self.matches = 0

   def process(self, row):
      code = row[4]
     import re
     if re.search(r'\[[A-Za-z][0-9]+\][0-9]+[A-Za-z]{2}[0-9]+#[0-9]+', code) is None:
         self.match += 1

   def value(self):
      return self.matches

import csv
col0_sum = SumColumn()
col3_sum = SumColumn(3, 2.45)
col5_6_add = ColumnAdder(5,6)
col4_matches = ColumnMatcher()

for row in csv.reader(open("myfile.csv")):
    col0_sum.process(row)
    col3_sum.process(row)
    col5_6_add.process(row)
    col4_matches.process(row)

print col0_sum.value()
print col3_sum.value()
print col5_6_add.value()
print col4_matches.value()

这段代码被输入到SO中,这是一件乏味的事情-几乎没有语法等。

仅出于说明目的-不能太实际地理解。

一切都是Python中的对象:这也意味着功能。
因此,无需像sotapme一样定义特殊的类来像这些类的实例一样构造函数,因为我们定义的每个函数在“类的实例”意义上已经是一个对象。

现在,如果某人需要创建多个相同类型的函数,例如,每个函数都添加了一个精确CSV文件列的所有值,那么正确的是,通过重复的过程来创建许多函数,这是正确的。
在这一点上,提出了一个问题:使用函数工厂或类?

从个性上讲,我更喜欢函数工厂方式,因为它不太冗长。
我还发现在Theran的回答这里 ,它的也比较快。

在下面的代码中,我使用了一个带有globals()的技巧,为通过函数工厂创建的每个函数赋予特定的名称。 有人会说这很糟糕,但我不知道为什么。 如果还有另一种方法可以做到这一点,我将很高兴学习它。

在代码中,一个函数工厂构建了3个函数,我让其中一个由普通的普通定义(op3)定义。

Python太棒了!

import csv
import re

# To create a CSV file
with open('Data.csv','wb') as csvhandle:
    hw = csv.writer(csvhandle)
    hw.writerows( ((2,10,'%%',3000,'-statusOK-'),
                   (5,3,'##',500,'-modo OOOOKKK-'),
                   (1,60,'**',700,'-- anarada-')) )
del hw

# To visualize the content of the CSV file
with open(r'Data.csv','rb') as f:
    print "The CSV file at start :\n  "+\
          '\n  '.join(map(repr,csv.reader(f)))


def run_funcs_on_CSVfile(FUNCS,CSV):
    with open(CSV,'rb') as csvhandle:
        for f in FUNCS:
            # this is necessary for functions not created via
            # via a function factory but via plain definition
            # that defines only the attribute col of the function
            if 'field' not in f.__dict__:
                f.field = f.col - 1
                # columns are numbered 1,2,3,4,...
                # fields are numbered 0,1,2,3,...
        for row in csv.reader(csvhandle):
            for f in FUNCS:
                f(row[f.field])

def SumColumn(name,col,start=0):
    def g(s):
        g.kept += int(s)
    g.kept = start
    g.field = col -1
    g.func_name = name
    globals()[name] = g

def MultColumn(name,col,start=1):
    def g(s):
        g.kept *= int(s)
    g.kept = start
    g.field = col - 1
    g.func_name = name
    globals()[name] = g

def ColumnMatcher(name,col,pat,start = 0):
    RE = re.compile(pat)
    def g(s,regx = RE):
        if regx.search(s):
            g.kept += 1
    g.kept = start
    g.field = col - 1
    g.func_name = name
    globals()[name] = g

SumColumn('op1',1)
MultColumn('op2',2)
ColumnMatcher('op4',5,'O+K')

def op3(s):
    s = int(s)
    if s%2:
        op3.kept += (2*s)
    else:
        op3.kept += s
op3.kept = 0
op3.col = 4


print '\nbefore:\n  ' +\
      '\n  '.join('%s.kept == %d'
                % (f.func_name,  f.kept)
                for f in (op1,op2,op3,op4) )

# The treatment is done here
run_funcs_on_CSVfile((op2,op3,op4,op1),r'Data.csv')
# note that the order of the functions in the tuple
# passed as argument can be any either one or another


print '\nafter:\n  ' +\
      '\n  '.join('%s(column %d) in %s.kept == %d'
                % (f.func_name, f.field+1, f.func_name, f.kept)
                for f in (op1,op2,op3,op4) )

结果。

The CSV file at start :
  ['2', '10', '%%', '3000', '-statusOK-']
  ['5', '3', '##', '500', '-modo OOOOKKK-']
  ['1', '60', '**', '700', '-- anarada-']

before:
  op1.kept == 0
  op2.kept == 1
  op3.kept == 0
  op4.kept == 0

after:
  op1(column 1) in op1.kept == 8
  op2(column 2) in op2.kept == 1800
  op3(column 4) in op3.kept == 4200
  op4(column 5) in op4.kept == 2

暂无
暂无

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

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