簡體   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