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. RocketMQ基本概念

    RocketMQ基本概念 一.生产者 生产者发送业务系统产生的消息给broker.RocketMQ提供了多种发送方式:同步的.异步的.单向的. 1.1 生产者组 具有相同角色的生产者被分到一组.假如原 ...

  2. Python 字符串操作 starswitch() find() re.IGNORECASE replace() join()

    检测开头&结尾开头:startswith()url = 'http://www.python.org' url.startswith('http') >>>True 结尾:e ...

  3. css基础教程

    css规则有两个主要部分构成:选择器,以及一条或多条声明. 值的不同写法和单位: 可以使用十六进制设置颜色值:#ff0000; 为节约字节,使用css缩写形式:#f00: 类选择器:以一个点号显示. ...

  4. Python 第八阶段 学习记录之---算法

    算法(Algorithm): 一个计算过程, 解决问题的方法 1.递归的两个特点 - 调用自身 - 结束条件 时间复杂度 - 时间复杂度是用来估计算法运行时间的一个式子(单位) - 一般来说,时间复杂 ...

  5. linux下列出所有连接到你的Server的IP地址

    linux下列出所有连接到你的Server的IP地址 最近要做一个检查所有连接到主机的IP的脚本,google到一篇老外写的文章 <List all IP addresses connected ...

  6. php配置可被设定范围

    PHP中的每个指令都有其所属的模式,这些模式决定这一个PHP指定在何时何地.是否能被设定.例如有些指令可以在 PHP 脚本中用 ini_set() 来设定,而有些则只能在php.ini 或 httpd ...

  7. python -yield理解

    参考:https://foofish.net/iterators-vs-generators.html 从网上看到一个面试题,求最后的输出结果: def add(n, i): return n+ide ...

  8. SQL 连接(内连接,外连接)

    内连接 现在有两张表,学生表student1,成绩表SC1,两张表的数据如下 现在要对两张表做连接查询,连接一般需要写条件,where 或者 on 后面 , select * from student ...

  9. eq

    <a class="s">1</a> <a class="s">2</a> <a class=" ...

  10. OLTP和OLAP的区别

    OLTP和OLAP的区别 联机事务处理OLTP(on-line transaction processing) 主要是执行基本日常的事务处理,比如数据库记录的增删查改.比如在银行的一笔交易记录,就是一 ...