如何在Python中读取CSV文件?

举报
Yuchuan 发表于 2021/02/24 14:21:11 2021/02/24
【摘要】 Python中读取CSV文件学习

您知道将表格数据存储到纯文本文件背后的机制是什么吗?答案是CSV(逗号分隔值)文件,该文件允许将数据转换为纯文本格式。在这篇文章中关于“在Python如何阅读CSV文件”中,我们将学习如何读,写和解析的CSV文件的Python

将详细讨论以下方面:

让我们开始吧。

什么是CSV文件及其用途?

CSV(逗号分隔值)是一种纯文本文件格式,用于存储表格数据(例如电子表格或数据库)。它本质上存储的表格数据包括数字和纯文本文本。大多数在线服务使用户可以自由地将网站中的数据导出为CSV文件格式。CSV文件通常会在Excel中打开,几乎所有数据库都具有不同的特定工具以允许导入相同的文件。

文件的每一行都称为记录。每个记录由用逗号分隔 的字段组成,这些字段也称为“定界符”,这是默认定界符,其他记录包括pipe(|),分号(;)。下面给出的是一个普通CSV文件的结构,以逗号分隔,我正在使用一个泰坦尼克号CSV文件。

结构

Passenger,Id,Survived,Pclass,Name,Sex.Age
1,0,3 Braund, Mr. Owen Harris ,male, 22
2,1,1 Cumings, Mrs. John Bradley (Florence Briggs Thayer), female,38
3,1,3 Heikkinen, Miss. Laina ,female, 26
4,1,1 Futrelle, Mrs. Jacques Heath (Lily May Peel),female,35

继续说说使用CSV文件格式的原因。

为什么使用CSV文件格式?

CSV是纯文本文件,它使数据交换更容易,也更易于导入到电子表格或数据库存储中。例如:您可能希望将某个统计分析的数据导出到CSV文件,然后将其导入电子表格以进行进一步分析。总体而言,它使用户可以通过编程轻松地体验工作。任何支持文本文件或字符串操作的语言(例如Python)都可以
直接使用CSV文件。

继续前进,让我们看看Python如何原生使用CSV。

Python CSV模块

Python使用的CSV软件包是标准库的一部分,因此您无需安装它。

import csv

现在,让我向您展示不同的CSV功能。

CSV模块功能

在CSV模块下,您可以找到以下功能:

Functions

Description

描述

csv.field_size_limit

It returns the maximum field size

返回最大字段大小

csv.get_dialect

Fetches the dialect associated with name

获取与名称关联的方言

csv.list_dialects

Displays all the registered dialects

显示所有已注册的方言

csv.reader

Read data from csv file

从CSV文件读取数据

csv.register_dialect

Dialect associated with a name

与姓名相关的方言

 csv.writer

Writes data to a csv file

将数据写入CSV文件

 csv.unregister_dialect

It deletes the dialect associated with the name dialect registry

它删除与名称方言注册表关联的方言

 csv.QUOTE_ALL

Quotes everything irrespective of the type

引用所有类型的所有内容

 csv.QUOTE_MINIMAL

Quotes special character field

引号特殊字符字段

csv.QUOTE_NONNUMERIC

Quotes fields that are not numeral

引用非数字的字段

csv.QUOTE_NONE

  Doesn’t quote anything in output

在输出中不引用任何内容

让我们继续前进,从Python CSV文件上不同操作的编码角度来看。

Python中CSV文件的操作

加载CSV文件后,您可以执行多种操作。我将在Python中显示对CSV文件的读取和写入操作。

 在Python中读取CSV文件:

import csv 
 
with open('Titanic.csv','r') as csv_file: #Opens the file in read mode
    csv_reader = csv.reader(csv_file) # Making use of reader method for reading the file
 
    for line in csv_reader: #Iterate through the loop to read line by line
        print(line)

输出:

在Python中读取CSV文件

在这里,从输出中可以看到,我已经使用了Titanic CSV File。并且所有字段都用逗号分隔,文件被读入Python。

继续前进,让我们看看如何写入CSV文件

用Python写入CSV文件:

import csv
 
with open('Titanic.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
 
    with open('new_Titanic.csv', 'w') as new_file: # Open a new file named 'new_titanic.csv' under write mode
        csv_writer = csv.writer(new_file, delimiter=';') #making use of write method
 
        for line in csv_reader: # for each file in csv_reader
            csv_writer.writerow(line) #writing out to a new file from each line of the original file

out:

在Python-Edureka中写入CSV读取CSV文件

现在,这种使用读写器方法处理CSV文件的方法是最常见的方法之一。让我们继续前进,看看如何使用python字典来做同样的事情。

读取CSV文件作为字典:

import csv 
 
with open('Titanic.csv','r') as csv_file: #Open the file in read mode
    csv_reader = csv.DictReader(csv_file) #use dictreader method to reade the file in dictionary
 
    for line in csv_reader: #Iterate through the loop to read line by line
        print(line)

输出:

Read-csv-dict-如何在Python-Edureka中读取CSV文件

从输出中可以看到,字段已被替换,它们现在充当字典的“键”。

让我们看看如何将CSV文件作为字典写入。

作为字典写入CSV文件

import csv 
 
mydict = [{'Passenger':'1', 'Id':'0', 'Survived':'3'}, #key-value pairs as dictionary obj
          {'Passenger':'2', 'Id':'1', 'Survived':'1'},
          {'Passenger':'3', 'Id':'1', 'Survived':'3'}]
 
fields = ['Passenger', 'Id', 'Survived'] #field names
 
filename = 'new_Titanic.csv' #name of csv file
 
with open('new_Titanic.csv', 'w')as new_csv_file: #open a new file 'new_titanic,csv' under write mode
    writer = csv.DictWriter(new_csv_file, fieldnames=fields) 
    writer.writeheader() #writing the headers(field names)
 
    writer.writerows(mydict) #writing data rows

输出:

Write-csv-dict-如何在python-Edureka中读取csv

让我们看看如何在python中将CSV文件读取为熊猫。

以熊猫格式读取CSV文件:

import pandas #install pandas package
 
result = pandas.read_csv('Titanic.csv') #read the csv file
 
print(result) # print result

输出:

Read-csv-pandas-如何在python-Edureka中读取csv文件

这使我们到文章“如何在Python中读取CSV文件”的结尾。我希望您对与CSV相关的所有概念,如何读写它,如何将CSV作为字典进行读写以及如何将CSV作为熊猫进行阅读都一目了然。

    确保尽可能多地练习并恢复经验

    【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
    • 点赞
    • 收藏
    • 关注作者

    评论(0

    0/1000
    抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    举报
    请填写举报理由
    0/200