如何在Python中读取CSV文件?详细介绍

2021年3月9日16:02:13 发表评论 634 次浏览

一种CSV(逗号分隔值)文件是纯文本文档的一种形式, 它使用特定格式来组织表格信息。 CSV文件格式是有界的文本文档, 使用逗号来区分值。文档中的每一行都是一个数据日志。每个日志由一个或多个字段组成, 并用逗号分隔。它是用于导入和导出电子表格和数据库的最流行的文件格式。

读取CSV文件

可以使用多种方式读取CSV文件, CSV模块或大熊猫图书馆。

  • csv模块:CSV模块是Python中的模块之一, 它提供用于以CSV文件格式读取和写入表格信息的类。
  • 熊猫图书馆:pandas库是开放源代码Python库之一, 它为Python编程提供了高性能, 便捷的数据结构以及数据分析工具和技术。

在Python中读取CSV文件格式:

考虑以下名为" Giants.CSV"的CSV文件:

在Python中读取CSV文件1

使用csv.reader():

首先, 使用

打开()

处于" r"模式(指定打开文件时为读取模式)的方法, 该方法返回文件对象, 然后使用

读者()

CSV模块的方法, 该方法返回遍历指定CSV文档中各行的阅读器对象。

注意:关键字" with"与open()方法一起使用, 因为它可以简化异常处理并自动关闭CSV文件。

import csv
  
# opening the CSV file
with open ( 'Giants.csv' , mode = 'r' )as file :
    
   # reading the CSV file
   csvFile = csv.reader( file )
  
   # displaying the contents of the CSV file
   for lines in csvFile:
         print (lines)

输出如下:

['Organiztion', 'CEO', 'Established']
['Alphabet', 'Sundar Pichai', '02-Oct-15']
['Microsoft', 'Satya Nadella', '04-Apr-75']
['Aamzon', 'Jeff Bezos', '05-Jul-94']

在上面的程序中, reader()方法用于读取Giants.csv文件, 该文件将数据映射到列表中。

使用csv.DictReader()类:

与以前的方法类似, 首先使用

打开()

方法, 然后使用

DictReader

csv模块的类, 类似于常规阅读器, 但是将CSV文件中的信息映射到字典中。文件的第一行包含字典键。

import csv
  
# opening the CSV file
with open ( 'Giants.csv' , mode = 'r' ) as file :    
         
        # reading the CSV file
        csvFile = csv.DictReader( file )
  
        # displaying the contents of the CSV file
        for lines in csvFile:
             print (lines)

输出如下:

OrderedDict([[('Organiztion', 'Alphabet'), ('CEO', 'Sundar Pichai'), ('Founded', '02 -Oct-15')])OrderedDict([('Organiztion', 'Microsoft' ), (" CEO", " Satya Nadella"), (" Founded", " 04-Apr-75")]) ), ('已建立', '05 -Jul-94')])

使用pandas.read_csv()方法:

使用pandas库函数读取CSV文件非常简单容易。这里

read_csv()

pandas库的方法用于从CSV文件读取数据。

import pandas
  
# reading the CSV file
csvFile = pandas.read_csv( 'Giants.csv' )
  
# displaying the contents of the CSV file
print (csvFile)

输出如下:

Organiztion            CEO Established
0    Alphabet  Sundar Pichai   02-Oct-15
1   Microsoft  Satya Nadella   04-Apr-75
2      Aamzon     Jeff Bezos   05-Jul-94

在上面的程序中, 熊猫库的csv_read()方法读取Giants.csv文件并将其数据映射到2D列表中。

注意:了解更多有关pandas.csv_read()的信息点击这里.

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: