加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python操作csv文件实例详解

发布时间:2020-12-17 08:13:24 所属栏目:Python 来源:网络整理
导读:一、Python读取csv文件 说明:以Python3.x为例 #读取csv文件方法1import csvcsvfile = open('csvWrite.csv',newline='')#打开一个文件csvReader = csv.reader(csvfile)#返回的可迭代类型print(type(csvReader))for content in csvReader: print(content)csvf

一、Python读取csv文件

说明:以Python3.x为例

#读取csv文件方法1
import csv
csvfile = open('csvWrite.csv',newline='')#打开一个文件
csvReader = csv.reader(csvfile)#返回的可迭代类型
print(type(csvReader))
for content in csvReader:
  print(content)
csvfile.close()#关闭文件
//运行结果如下:
<class '_csv.reader'>
['编号','网址','关键字']
['1','http://nnzhp.cn/','牛牛']
['2','http://www.baidu.com/','百度']
['3','http://www.jd.com/','京东']
['4','http://http://www.cnblogs.com/hhfzj/','自己博客']
#读取csv文件方法2
import csv
with open('csvWtite.csv',newline='') as csvfile:#此方法:当文件不用时会自动关闭文件
  csvReader = csv.reader(csvfile)
  for content in csvReader:
    print(content)

二、写数据到csv文件

import csv
csvfile = open('csvWrite.csv','w',newline='')
writer = csv.writer(csvfile)
writer.writerow(('编号','关键字'))
ss= [
 ('1','牛牛'),('2','百度'),('3','京东')
]
ccs = ('4','自己博客')
writer.writerows(ss)
writer.writerow(ccs)
csvfile.close()

说明:以Python3.x为例

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读