亚洲欧洲国产欧美一区精品,激情五月亚洲色五月,最新精品国偷自产在线婷婷,欧美婷婷丁香五月天社区

      python

      當前位置:中華考試網(wǎng) >> python >> python編程基礎(chǔ) >> 文章內(nèi)容

      python如何讀取csv

      來源:中華考試網(wǎng)  [2020年11月2日]  【

        普通方法讀。

        1 with open("fileName.csv") as file:

        2 for line in file:

        3 print line

        用CSV標準庫讀取:

        1 import csv

        2 csv_reader = csv.reader(open("fileName.csv"))

        3 for row in csv_reader:

        4 print row

        用pandas讀。

        1 import pandas as pd

        2 data = pd.read_csv("fileName.csv")

        3 print data

        4

        5 data = pd.read_table("fileName.csv",sep=",")

        6 print data

        Python怎么讀取csv的某行

        csv是Comma-Separated Values的縮寫,是用文本文件形式儲存的表格數(shù)據(jù)

        就可以存儲為csv文件,文件內(nèi)容是:

        No.,Name,Age,Score

        1,Apple,12,98

        2,Ben,13,97

        3,Celia,14,96

        4,Dave,15,95

        假設(shè)上述csv文件保存為"A.csv",如何用Python像操作Excel一樣提取其中的一行,也就是一條記錄,利用Python自帶的csv模塊,有兩種方法可以實現(xiàn):

        第一種方法使用reader函數(shù),接收一個可迭代的對象(比如csv文件),能返回一個生成器,就可以從其中解析出csv的內(nèi)容:比如下面的代碼可以讀取csv的全部內(nèi)容,以行為單位:import csv

        with open('A.csv','rb') as csvfile:

        reader = csv.reader(csvfile)

        rows = [row for row in reader]

        print rows得到:[['No.', 'Name', 'Age', 'Score'],

        ['1', 'Apple', '12', '98'],

        ['2', 'Ben', '13', '97'],

        ['3', 'Celia', '14', '96'],

        ['4', 'Dave', '15', '95']]

        要提取其中第二行,可以用下面的代碼:

        import csv

        with open('A.csv','rb') as csvfile:

        reader = csv.reader(csvfile)

        for i,rows in enumerate(reader):

        if i == 2:

        row = rows

        print row 得到:['2', 'Ben', '13', '97']這種方法是通用的方法,要事先知道行號,比如Ben的記錄在第2行,而不能根據(jù)'Ben'這個名字查詢。這時可以采用第二種方法:

        第二種方法是使用DictReader,和reader函數(shù)類似,接收一個可迭代的對象,能返回一個生成器,但是返回的每一個單元格都放在一個字典的值內(nèi),而這個字典的鍵則是這個單元格的標題(即列頭)。用下面的代碼可以看到DictReader的結(jié)構(gòu):

        import csv

        with open('A.csv','rb') as csvfile:

        reader = csv.DictReader(csvfile)

        rows = [row for row in reader]

        print rows得到:

        [{'Age': '12', 'No.': '1', 'Score': '98', 'Name': 'Apple'},

        {'Age': '13', 'No.': '2', 'Score': '97', 'Name': 'Ben'},

        {'Age': '14', 'No.': '3', 'Score': '96', 'Name': 'Celia'},

        {'Age': '15', 'No.': '4', 'Score': '95', 'Name': 'Dave'}]

        如果我們想用DictReader讀取csv的某一列,就可以用列的標題查詢:

        import csv

        with open('A.csv','rb') as csvfile:

        reader = csv.DictReader(csvfile)

        for row in reader:

        if row['Name']=='Ben':

        print row就得到:

        {'Age': '13', 'No.': '2', 'Score': '97', 'Name': 'Ben'}可見,DictReader很適合讀取csv的的行(記錄)。

      python課程免費試聽預約

      • 地區(qū):
      • 姓名:
      • 手機:

        Python讀取csv的方法

        1.以行為單位存儲csv內(nèi)容:

        import csv

        with open('A.csv','rb') as csvfile:

        reader = csv.reader(csvfile)

        rows= [row for row in reader]

        print rows

        得到

        [['No.', 'Name', 'Age', 'Score'],

        ['1', 'Apple', '12', '98'],

        ['2', 'Ben', '13', '97'],

        ['3', 'Celia', '14', '96'],

        ['4', 'Dave', '15', '95']]

        2.讀取csv的某一列 (用列的序號):

        import csv

        with open('A.csv','rb') as csvfile:

        reader = csv.reader(csvfile)

        column = [row[2] for row in reader]

        print column

        得到

        ['Age', '12', '13', '14', '15']

        3.讀取csv的某一行 (用行的序號):

        import csv

        with open('A.csv','rb') as csvfile:

        reader = csv.reader(csvfile)

        for i,rows in enumerate(reader):

        if i == 2:

        row = rows

        print row

        得到

        ['2', 'Ben', '13', '97']

        4.使用字典存儲csv內(nèi)容:

        import csv

        with open('A.csv','rb') as csvfile:

        reader = csv.DictReader(csvfile)

        column = [row for row in reader]

        print column

        得到

        [{'Age': '12', 'No.': '1', 'Score': '98', 'Name': 'Apple'},

        {'Age': '13', 'No.': '2', 'Score': '97', 'Name': 'Ben'},

        {'Age': '14', 'No.': '3', 'Score': '96', 'Name': 'Celia'},

        {'Age': '15', 'No.': '4', 'Score': '95', 'Name': 'Dave'}]

        5.讀取csv的某一列(用列的標題):

        import csv

        with open('A.csv','rb') as csvfile:

        reader = csv.DictReader(csvfile)

        column = [row['Age'] for row in reader]

        print column

        得到

        ['12', '13', '14', '15']

        6.讀取csv的某一行(用行的標題):

        import csv

        with open('A.csv','rb') as csvfile:

        reader = csv.DictReader(csvfile)

        for row in reader:

        if row['Name']=='Ben':

        print row

        得到

        {'Age': '13', 'No.': '2', 'Score': '97', 'Name': 'Ben'}

        python怎么寫CSV文件

        讀文件時,我們把csv文件讀入列表中,寫文件時會把列表中的元素寫入到csv文件中。

        list = ['1', '2','3','4']

        out = open(outfile, 'w')

        csv_writer = csv.writer(out)

        csv_writer.writerow(list)

        可能遇到的問題:直接使用這種寫法會導致文件每一行后面會多一個空行。

        解決辦法如下:

        out = open(outfile, 'w', newline='')

        csv_writer = csv.writer(out, dialect='excel')

        csv_writer.writerow(list)

        參考如下:

        在stackoverflow上找到了比較經(jīng)典的解釋,原來 python3里面對 str和bytes類型做了嚴格的區(qū)分,不像python2里面某些函數(shù)里可以混用。所以用python3來寫wirterow時,打開文件不要用wb模式,只需要使用w模式,然后帶上newline=''。

        3down vote

        In Python 2.X, it was required to open the csvfile with 'b' because the csv module does its own line termination handling.

        In Python 3.X, the csv module still does its own line termination handling, but still needs to know an encoding for Unicode strings. The correct way to open a csv file for writing is:

        outputfile=open("out.csv",'w',encoding='utf8',newline='')

        encoding can be whatever you require, but newline='' suppresses text mode newline handling. On Windows, failing to do this will write \r\r\n file line endings instead of the correct \r\n. This is mentioned in the 3.X csv.reader documentation only, but csv.writer requires it as well.

      責編:fushihao
      • 會計考試
      • 建筑工程
      • 職業(yè)資格
      • 醫(yī)藥考試
      • 外語考試
      • 學歷考試