python读取CSV(python读取csv文件的路径)

http://www.itjxue.com  2023-04-09 01:31  来源:未知  点击次数: 

python中读取csv文件

python中读取csv方法有3种:

第一种,普通方法读取(open函数打开,然后使用for循环读取内容);

第二种,使用用CSV标准库读取;

第三种,用pandas模块读取。

python中怎么读取csv文件

Python读取CSV文件方法如下:

如下是一个CVS文件

使用Python打开CSV可以直接使用open函数打开,然后使用reader函数读取内容,实现代码如下:

运行结果如下:

更多Python相关技术文章,请访问Python教程栏目进行学习!以上就是小编分享的关于python中怎么读取csv文件的详细内容希望对大家有所帮助,更多有关python教程请关注环球青藤其它相关文章!

python—CSV的读写

1.写入csv数据

import csv

header=['class','name','sex','height','year']

rows=[

[1,'xiaoming','male',168,23],

[1,'xiaohong','female',162,22],

[2,'xiaozhang','female',158,21],

[2,'xiaoli','male',158,21]

]

with open('csvdir.csv','w',newline='')as f:? ? ? ? ? #newline=" "是为了避免写入之后有空行

????????ff=csv.writer(f)

????????ff.writerow(header)

? ? ????ff.writerows(rows)

2.在写入字典序列类型数据的时候,需要传入两个参数,一个是文件对象——f,一个是字段名称——fieldnames,到时候要写入表头的时候,只需要调用writerheader方法,写入一行字典系列数据调用writerrow方法,并传入相应字典参数,写入多行调用writerows ?

import csv

headers = ['class','name','sex','height','year']

rows = [

? ? ? ? {'class':1,'name':'xiaoming','sex':'male','height':168,'year':23},

? ? ? ? {'class':1,'name':'xiaohong','sex':'female','height':162,'year':22},

? ? ? ? {'class':2,'name':'xiaozhang','sex':'female','height':163,'year':21},

? ? ? ? {'class':2,'name':'xiaoli','sex':'male','height':158,'year':21},

? ? ]

with open('test2.csv','w',newline='')as f:

? ? ? f_csv = csv.DictWriter(f,headers)

? ? ? f_csv.writeheader()

? ? ? f_csv.writerows(rows)

注意:列表和字典形式的数据写入是不一样的!!!!!!

3.csv的读取,和读取文件差不多:

import csv?

with open('test.csv')as f:

? ? f_csv = csv.reader(f)

? ? for row in f_csv:

? ? ? ? print(row)

怎么用python读取csv数据

这两天刚好看到,Python CookBook上有说到。这里是三种读取csv的方法。

文件格式是这样的

Region,DATE_,RAW_ACU

zh_ch,Jan 27 2017,208172

import?csv

from?collections?import?namedtuple

#?with?open('data.csv')?as?f:

#?????f_csv?=?csv.reader(f)

#?????headers?=?next(f_csv)

#?????for?row?in?f_csv:

#?????????#?print(row)

#?????????print(row[0],?row[1])

#?with?open('data.csv',?encoding='utf-8-sig')?as?f:

#?????f_csv?=?csv.reader(f)

#?????headers?=?next(f_csv)

#?????print(headers)

#?????Row?=?namedtuple('Row',?headers)

#?????for?r?in?f_csv:

#?????????row?=?Row(*r)

#?????????print(row.Region,?row.DATE_)

with?open('data.csv',?encoding='utf-8-sig')?as?f:

????f_csv?=?csv.DictReader(f)

????for?row?in?f_csv:

????????print(row['DATE_'],?row)

具体可以看这个文档。。

(责任编辑:IT教学网)

更多

推荐其他源码文章