淺談如何使用python 處理CSV文件的數據

1、引言

聲明:本人也是剛接觸CSV數據,所以記錄下來主要是爲了日後參考。本文的知識點含金量不高,高手可以直接跳過,小白可以作爲參考。

由於工作需要需要對保存對.txt文件的數據進行處理(數據量較大,一次分析20多MBytes)。主要目的是想將保存在txt文件中的數據整理到excel中,通過簡單處理繪畫出數據之間的關係變化曲線。需要處理的數據大致如下:

  ff25,  31c5,  31c5,  13f8,  19d2,   d65,  a65a,   265,   260,   25b,   264,  2d90,     1,     1
  ff25,  31c5,  31c5,  13f8,  19d2,   d65,  a65a,   265,   260,   25b,   264,  2d90,     1,     1
  ff6f,  30e2,  30e8,  1429,  19dc,   d71,  1815,   2cb,   2ca,   2ca,   2ca,  3030,     1,     1
  ff6e,  30e2,  30e8,  1429,  19dc,   d71,  1815,   2cb,   2ca,   2ca,   2ca,  3030,     1,     1
  ff6d,  30e2,  30e8,  1429,  19dc,   d71,  1815,   2cb,   2ca,   2ca,   2ca,  3030,     1,     1
  ff6e,  30e2,  30e8,  1429,  19dc,   d71,  1815,   2cb,   2ca,   2ca,   2ca,  3030,     1,     1
  ff6f,  30e2,  30e8,  1429,  19dc,   d71,  1815,   2cb,   2ca,   2ca,   2ca,  3030,     1,     1
  ff6e,  30e2,  30e8,  1429,  19dc,   d71,  1815,   2cb,   2ca,   2ca,   2ca,  3030,     1,     1
  ff6e,  30e2,  30e8,  1429,  19dc,   d71,  1815,   2cb,   2ca,   2ca,   2ca,  3030,     1,     1
  ff6f,  30e2,  30e8,  1429,  19dc,   d61,  8184,   2cb,   2ca,   2ca,   2ca,  3030,     0,     1
  ff61,  30e2,  30e8,  1429,  19dc,   d61,  8184,   2cb,   2ca,   2ca,   2ca,  3030,     0,     1

熟悉CSV的朋友,看到上面數據顯示形式應該就能想到這種數據存放形式剛好滿足CSV的格式要求。所以,針對上述txt的文件,我們可以直接將文件擴展名由.txt修改爲.csv,這樣就可以得到csv格式的數據,在此基礎上可以藉助python的csv模塊、list數據類型等對數據進行處理,方便、快捷、效果還不錯。

2、CSV文件的處理

2.1 python的csv模塊介紹

需要使用python自帶模塊csv,關於此模塊的詳細介紹可以使用help命令查看(或者在安裝python的目錄下找到:python2.7.1\lib\csv.py查看),部分信息如下:

>>> import csv
>>> help(csv)
Help on module csv:

NAME
    csv - CSV parsing and writing.

FILE
    d:\program files\python2.7.1\lib\csv.py

DESCRIPTION
    This module provides classes that assist in the reading and writing
    of Comma Separated Value (CSV) files, and implements the interface
    described by PEP 305.  Although many CSV files are simple to parse,
    the format is not formally defined by a stable specification and
    is subtle enough that parsing lines of a CSV file with something
    like line.split(",") is bound to fail.  The module supports three
    basic APIs: reading, writing, and registration of dialects.
    
    
    DIALECT REGISTRATION:
    
    Readers and writers support a dialect argument, which is a convenient
    handle on a group of settings.  When the dialect argument is a string,
    it identifies one of the dialects previously registered with the module.
    If it is a class or instance, the attributes of the argument are used as
    the settings for the reader or writer:
    
        class excel:
            delimiter = ','
            quotechar = '"'
            escapechar = None
            doublequote = True
            skipinitialspace = False
            lineterminator = '\r\n'
            quoting = QUOTE_MINIMAL

(1)delimiter :分割符

        默認使用的分割符是英文下的',',這就意味着在使用csv的reader()或writer()方法時,只能處理分割符是','的文件,此時如果文件中的分割符是其他字符(製表符tab:'\t' 、 英文下的分號:‘;’),比如文件分割符使用的是“;”,此時如下在調用reader()或writer()函數是,仍然使用默認的Dialect(編碼風格,默認的是excel的編碼風格)就會得到如下錯誤:

<type '_csv.reader'>

Traceback (most recent call last):
  File "C:\Users\10217463\Desktop\csv_read.py", line 26, in <module>
    main()
  File "C:\Users\10217463\Desktop\csv_read.py", line 23, in main
    func_read_csv_file("csv_data_001.csv")
  File "C:\Users\10217463\Desktop\csv_read.py", line 14, in func_read_csv_file
    print np.short(int(stu[i],16))
ValueError: invalid literal for int() with base 16: 'ff6f;  30e2;  30e8;  1429;  19dc;   d71;  1815;   2cb;   2ca;   2ca;   2ca;  3030;     1;     1'

此時就需要使用csv的register_dialect(),此函數主要功能就是創建一個自定義的Dialect,此函數的說明:

register_dialect(...)
        Create a mapping from a string name to a dialect class.
        dialect = csv.register_dialect(name, dialect)

所以針對上述異常,可以創建如下的Dialect,然後在reader()中使用自定義的Dialect,具體代碼如下:

import csv as cv
import numpy as np
def func_read_csv_file(filepath):
    'read csv file'
    #read csv file
    cv.register_dialect('MyDialect', delimiter=';',doublequote=False,quotechar='',
                         lineterminator='\n',escapechar='',quoting=cv.QUOTE_NONE)
    with open(filepath,'r') as pCSVFile:
        Reader = cv.reader(pCSVFile,'MyDialect')
        print type(Reader)
        for stu in Reader:
            #print stu,type(stu),len(stu)
            for i in range(len(stu)):
                print np.short(int(stu[i],16))

(2)quotechar:引用符

         默認使用的引用符是英文下的單引號'''',用於帶有特殊字符(如分隔符)的字段的引用符號。

(3)escapechar :用於對分隔符進行轉義的字符串(如果quoting被設置爲csv.QUOTE_NONE的話)。默認禁用。

(4)doublequote :如何處理字段內的引用符號。如果爲True,則雙寫,默認爲TRUE。

(5)skipinitialspace :忽略分隔符後面的空白符。默認爲False

(6)lineterminator = '\r\n' :用於寫操作的行結束符,默認爲“\r\n”。讀操作將忽略此選項。

        specifies the character sequence which should terminate rows.

(7)quoting = QUOTE_MINIMAL:

           quoting - controls when quotes should be generated by the writer.
            It can take on any of the following module constants:
    
            csv.QUOTE_MINIMAL means only when required, for example, when a
                field contains either the quotechar or the delimiter
            csv.QUOTE_ALL means that quotes are always placed around fields.
            csv.QUOTE_NONNUMERIC means that quotes are always placed around
                fields which do not parse as integers or floating point
                numbers.
            csv.QUOTE_NONE means that quotes are never placed around fields.

關於編碼風格屬性的詳細信息可以在PEP 305中查詢。

2.2 csv的常用方法簡介

(1)register_dialect(...)

        此函數主要應用於字符串名稱和編碼風格類之間的映射,具體應用如下:

 csv.register_dialect('MyDialect', delimiter=';',doublequote=True,quotechar='',
                         lineterminator='\n',escapechar='',quoting=csv.QUOTE_NONE)

MyDialect就是自定義的編碼風格的字符串名稱。

(2)reader(...)

 csv_reader = reader(iterable [, dialect='excel'] 
                    [optional keyword args])
 for row in csv_reader:
     process(row)

此方法主要應用於從csv文件中讀取數據。此函數的返回值csv_reader類型是<type '_csv.reader'>,每個row 實質上是一個list數據類型。這樣我們就可以對row使用list的諸多方法,如:切片、列表倒序、查找制定成員的索引等,也可以使用len()內置函數得到一個list的長度等等。

(3)writer(...)

 csv_writer = csv.writer(fileobj [, dialect='excel']
                                    [optional keyword args])
            for row in sequence:
                csv_writer.writerow(row)
        
            [or]
        
            csv_writer = csv.writer(fileobj [, dialect='excel']
                                    [optional keyword args])
            csv_writer.writerows(rows)
        
        The "fileobj" argument can be any object that supports the file API.

此方法的主要用途是將列表數據寫入csv文件。同樣,此方法的返回值csv_writer類型是<type '_csv.writer'>。

3、總結

以上記錄爲本人第一次使用python 的csv模塊處理csv文件的經歷,簡單記錄一下;如果有描述不對的地方歡迎指出。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章