在之前的文章中介绍过为什么python学习中会使用CSV文件格式?这边文章将会详细介绍python中不同的CSV功能和使用。
成都创新互联是一家专业提供防城企业网站建设,专注与网站设计、做网站、成都h5网站建设、小程序制作等业务。10年已为防城众多企业、政府机构等服务。创新互联专业网站制作公司优惠进行中。
一、CSV模块功能
在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教程:python中不同的CSV功能和使用
转载来源:http://www.gawzjz.com/qtweb2/news23/14123.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联