Python3 读取csv文件

方法一,panda包读取:

没有安装panda包需要先安装panda包:pip install pandas

读取csv数据:

import pandas as pd

cased = pd.read_csv('d:/dataname.csv')

若出现错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 2: invalid continuation byte

通过修改encoding值进行修改,如下:

cased = pd.read_csv('d:/dataname.csv',encoding='gb18030')

cased = pd.read_csv('d:/dataname.csv',encoding='gbk')

方法二,csv包读取:

python3中读取csv文件可以使用csv库,一般是自带的,不需要pip安装

读取csv文件:

import csv

casedata = csv.reader('d:/dataname.csv')

1、获取所有行

import csv

with open('d:/dataname.csv', 'r') as f:

    reader = csv.reader(f)

    print(type(reader))

    for row in reader:

        print(row)

2、获取某一行

with open('d:/dataname.csv', 'r') as f:

    reader = csv.reader(f)

    result = list(reader) 

    print(result[1])

3、获取某一列

import csv

with open('d:/dataname.csv', 'r') as f:

    reader = csv.reader(f)

    for i in reader:

        print(i[0])

你可能感兴趣的:(Python3 读取csv文件)