Python实现的简单读写csv文件操作示例

yipeiwu_com7年前Python基础

本文实例讲述了Python实现的简单读写csv文件操作。分享给大家供大家参考,具体如下:

python中有一个读写csv文件的包,直接import csv即可

新建test.csv

1.写

import csv
with open("test.csv","w",encoding='utf8') as csvfile:
  writer=csv.writer(csvfile)
  writer.writerow(["index","a_name","b_name"])
  writer.writerows([[0,'a1','b1'],[1,'a2','b2'],[2,'a3','b3']])

直接使用这种写法会导致文件每一行后面会多一个空行

解决的方法

用python3来写wirterow时,打开文件时使用w模式,然后带上newline=''

import csv
with open("test.csv","w",encoding='utf8',newline='') as csvfile:
  writer=csv.writer(csvfile)
  writer.writerow(["index","a_name","b_name"])
  writer.writerows([[0,'a1','b1'],[1,'a2','b2'],[2,'a3','b3']])

2.读

import csv
with open("test.csv","r") as csvfile:
  reader=csv.reader(csvfile)
  for line in reader:
    print(line)

更多Python相关内容感兴趣的读者可查看本站专题:《Python操作Excel表格技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

以windows service方式运行Python程序的方法

本文实例讲述了以windows service方式运行Python程序的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python # coding...

python 生成器生成杨辉三角的方法(必看)

用Python写趣味程序感觉屌屌的,停不下来 #生成器生成展示杨辉三角 #原理是在一个2维数组里展示杨辉三角,空的地方用0,输出时,转化为' ' def yang(line):...

python中的reduce内建函数使用方法指南

官方解释: Apply function of two arguments cumulatively to the items of iterable, from left to r...

python中subprocess批量执行linux命令

可以执行shell命令的相关模块和函数有: os.system os.spawn os.popen --废弃 popen --废弃 commands --废弃,3....

Tensorflow 实现分批量读取数据

之前的博客里使用tf读取数据都是每次fetch一条记录,实际上大部分时候需要fetch到一个batch的小批量数据,在tf中这一操作的明显变化就是tensor的rank发生了变化,我目前...