溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2021-04-30 10:03:14 來源:億速云 閱讀:178 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關(guān)python中不同的CSV功能和使用示例分析的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

python主要應(yīng)用領(lǐng)域有哪些

1、云計算,典型應(yīng)用OpenStack。2、WEB前端開發(fā),眾多大型網(wǎng)站均為Python開發(fā)。3.人工智能應(yīng)用,基于大數(shù)據(jù)分析和深度學(xué)習(xí)而發(fā)展出來的人工智能本質(zhì)上已經(jīng)無法離開python。4、系統(tǒng)運維工程項目,自動化運維的標配就是python+Django/flask。5、金融理財分析,量化交易,金融分析。6、大數(shù)據(jù)分析。

一、CSV模塊功能

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

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

二、Python中CSV文件操作

加載CSV文件后,您可以執(zhí)行多種操作。將在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

感謝各位的閱讀!關(guān)于“python中不同的CSV功能和使用示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI