python读取CSV文件

 

python中有一个读写csv文件的包,直接import csv即可。利用这个python包可以很方便对csv文件进行操作,一些简单的用法如下。

1. 读文件

csv_reader = csv.reader(open('data.file', encoding='utf-8'))
for row in csv_reader:
print(row)

例如有如下的文件

输出结果如下

['0.093700','0.139771','0.062774','0.007698']

['-0.022711','-0.050504','-0.035691','-0.065434']

['-0.090407','0.021198','0.208712','0.102752']

['-0.085235','0.009540','-0.013228','0.094063']

可见csv_reader把每一行数据转化成了一个list,list中每个元素是一个字符串

2. 写文件

读文件时,我们把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上找到了比较经典的解释,原来 python3里面对 str和bytes类型做了严格的区分,不像python2里面某些函数里可以混用。所以用python3来写wirterow时,打开文件不要用wb模式,只需要使用w模式,然后带上newline=''。

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.

链接:http://blog.csdn.net/lixiang0522/article/details/7755059

 
 
 class writer():
def __init__(self):
self.dict={
"标题":"标题",
"链接":"链接",
"服务":"服务",
"dsr":"dsr",
"店铺名":"店铺名",
"价格":"店铺名",
"付款人数":"付款人数",
"发货地":"发货地"
}
out = open("outfile.csv", 'w', newline='')
self.csv_writer = csv.writer(out, dialect='excel')
self.csv_writer.writerow(self.dict) def writer_to(self,key_value):
self.csv_writer.writerow(key_value) if __name__ == '__main__':
a=writer()
new={"链接":"http://www.baidu.com",'标题':'我是标题',}
a.dict.update(new)
print(a.dict)
a.writer_to(a.dict.values())

import csv

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains driver=['','']
colspan=['','']
try:
out = open('类目.csv', 'w', newline='')
except PermissionError:
print('文件被其他程序占用')
input('')
csv_writer = csv.writer(out, dialect='excel')
csv_writer.writerow(['宝贝ID','类目']) def open_chrome():
driver[0]=webdriver.Chrome()
driver[0].get('https://www.dianchacha.com')
input('请登陆后按回车:') def EC_located(one_group,value):
'''
目的:简化代码长度,参数1选择one或者group切换选中模式
:param value:要找的值【CSS选择器】
:return:选择到的对象
'''
wait = WebDriverWait(driver[0], 10)
if one_group=="one":
try:
ecl=wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,value)))
return ecl
except TimeoutException:
print(value,'1元素未加载成功,等待超时')
else:
try:
ecl=wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,value)))
return ecl
except TimeoutException:
print(value,'1元素---组---未加载成功,等待超时') def operating(ID):
#先获取ID输入框
driver[0].get('https://www.dianchacha.com/item/info/index/iid/'+ID)
html=driver[0].page_source
if '未能找到亲的宝贝' not in html:
colspans=EC_located('group','.colspan-1')
colspan[0]=str(colspans[1].text).replace('宝贝类目: ','')
else:
return operating(ID)
print(colspan) def writer_txt():
csv_writer.writerow([url[0],colspan[0]])
print('保存',url[0],colspan[0],'成功') url=['','']
def main():
open_chrome()
file = '宝贝ID.txt'
with open(file) as f:
for line in f.readlines():
url[0] = line
print(line)
operating(url[0])
writer_txt()
out.close()
print('已完成') if __name__ == '__main__':
main()

读文本写csv

python3读写csv文件的更多相关文章

  1. python3使用csv包,读写csv文件

    python操作csv,现在很多都用pandas包了,不过python还是有一个原始的包可以直接操作csv,或者excel的,下面举个例子说明csv读写csv文件的方法: import os impo ...

  2. (Python基础教程之十二)Python读写CSV文件

    Python基础教程 在SublimeEditor中配置Python环境 Python代码中添加注释 Python中的变量的使用 Python中的数据类型 Python中的关键字 Python字符串操 ...

  3. 用opencsv文件读写CSV文件

    首先明白csv文件长啥样儿: 用excel打开就变成表格了,看不到细节 推荐用其它简单粗暴一点儿的编辑器,比如Notepad++, csv文件内容如下: csv文件默认用逗号分隔各列. 有了基础的了解 ...

  4. 使用Python读写csv文件的三种方法

    Python读写csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 前言 逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是 ...

  5. python读写csv文件

    文章链接:https://www.cnblogs.com/cloud-ken/p/8432999.html Python读写csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 前言 逗 ...

  6. 利用JavaCSV API来读写csv文件

    http://blog.csdn.net/loongshawn/article/details/53423121 http://javacsv.sourceforge.net/ 转载请注明来源-作者@ ...

  7. 使用 Apache Commons CSV 读写 CSV 文件

    有时候,我们需要读写 CSV 文件,在这里给大家分享Apache Commons CSV,读写 CSV 文件非常方便. 具体官方文档请访问Apache Commons CSV. 官方文档已经写得很详细 ...

  8. C/C++读写csv文件

    博客转载自:http://blog.csdn.net/u012234115/article/details/64465398 C++ 读写CSV文件,注意一下格式即可 #include <ios ...

  9. JAVA读写CSV文件

    最近工作需要,需要读写CSV文件的数据,简单封装了一下 依赖读写CSV文件只需引用`javacsv`这个依赖就可以了 <dependency> <groupId>net.sou ...

随机推荐

  1. redis 列表(list)函数

    列表(list)函数 lPush 命令/方法/函数 Description Adds the string value to the head (left) of the list. Creates ...

  2. Python数据基础--列表、元组、字典、函数

    一.数据结构 列表(List)和元组 序列是Python中最基本的数据结构.序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推. Python有6个序列的内 ...

  3. html中div标签怎么用?

    div现在一般网页的布局都是使用的div+css来布局,div的话,就是通过. <div> <div><p></p></div> </ ...

  4. Spring:容器基本用法

    bean是Spring 最核心的东西,打个比方,假设Spring是一个水桶,那么bean就是水桶里的水,水桶离开水后,就没啥作用了.我们先来看一下bean的定义: public class Perso ...

  5. react中对于redux的封装

    const createStore = (reducer)=>{ //默认的state对象 let state = {}; //将所有订阅的事件存在在这个数组中 let listeners = ...

  6. shell的打印菜单

    #!/bash/bin cat  << EOF   #EOF是变量,可随便设置,但标准是EOF 1)hello world. 2)你好,世界. EOF

  7. json与bson区别

    bson是由10gen开发的一个数据格式,目前主要用于mongoDB中,是mongoDB的数据存储格式.bson基于json格式,选择json进行改造的原因主要是json的通用性及json的schem ...

  8. 用PIL库进行图像处理

    一.如果系统里没有安装PIL库的,请先到命令提示符输入“pip install pillow”进行安装 二.之后就可以参考以下的代码 from PIL import Image from pylab ...

  9. nginx 配置反向代理

    之前的前端是8123端口,使用此端口让nginx的反向代理. vim /etc/nginx/conf.d/80-fr.conf upstream cats{ server 127.0.0.1:8123 ...

  10. [译]RabbitMQ教程C#版 - 主题

    先决条件 本教程假定 RabbitMQ 已经安装,并运行在localhost标准端口(5672).如果你使用不同的主机.端口或证书,则需要调整连接设置. 从哪里获得帮助 如果您在阅读本教程时遇到困难, ...