python中不同的CSV功能和使用示例分析

这篇文章给大家分享的是有关python中不同的CSV功能和使用示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

创新互联建站专业为企业提供武宣网站建设、武宣做网站、武宣网站设计、武宣网站制作等企业网站建设、网页设计与制作、武宣企业网站模板建站服务,10余年武宣做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。

python主要应用领域有哪些

1、云计算,典型应用OpenStack。2、WEB前端开发,众多大型网站均为Python开发。3.人工智能应用,基于大数据分析和深度学习而发展出来的人工智能本质上已经无法离开python。4、系统运维工程项目,自动化运维的标配就是python+Django/flask。5、金融理财分析,量化交易,金融分析。6、大数据分析。

一、CSV模块功能

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

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文件:

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

读取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文件

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功能和使用示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

本文题目:python中不同的CSV功能和使用示例分析
网页网址:https://www.cdcxhl.com/article48/pgjoep.html

成都网站建设公司_创新互联,为您提供手机网站建设云服务器虚拟主机响应式网站定制开发

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

微信小程序开发