如何在Python中读取CSV文件?

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

将详细讨论以下方面:

    • 什么是CSV文件及其用途?
    • 为什么使用CSV文件格式?
    • Python CSV模块
      • CSV模块功能
    • 在Python中执行写入,读取CSV文件的操作

让我们开始吧。

什么是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)

输出:

在这里,从输出中可以看到,我已经使用了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:

现在,这种使用读写器方法处理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)

输出:

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

让我们看看如何将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

输出:

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

以熊猫格式读取CSV文件:

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

输出:

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

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

    合智互联客户成功服务热线:400-1565-661

    admin
    admin管理员

    上一篇:云原生2.0时代,企业都应该了解的容器安全
    下一篇:CPU高速缓存与极性代码设计

    留言评论

    暂无留言
    取消
    扫码支持