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. OpenStack-Neutron-Fwaas-代码【二】

    上一节从代码层面来讲解了fwaas的流程,这里通过具体查看iptables规则来说下应用规则的流程: 1.首先通过命令获取当前路由中的规则 #ip netns exec qrouter-[router ...

  2. 自己动手写java锁

    1.LockSupport的park和unpark方法的基本使用,以及对线程中断的响应性 LockSupport是JDK中比较底层的类,用来创建锁和其他同步工具类的基本线程阻塞原语.java锁和同步器 ...

  3. 2018-2019-2 网络对抗技术 20165335 Exp4 恶意代码分析

    实验内容: 一.使用schtacks进行系统运行监控,使用sysmon工具监控系统的具体进程,使用各种工具进行监控,并针对软件的启动回连,安装到目标机,以及其他的控制行为的分析,同时,对主机的注册表, ...

  4. Django数据查询方法总结

      __exact 精确等于 like ‘aaa’__iexact 精确等于 忽略大小写 ilike ‘aaa’__contains 包含 like ‘%aaa%’__icontains 包含 忽略大 ...

  5. Python hasattr() 函数

    hasattr() 函数用于判断对象是否包含对应的属性.(has attribute) hasattr(object, name) 参数 object -- 对象. name -- 字符串,属性名. ...

  6. Leetcode 存在重复元素 (219,220)

    219. 存在重复元素 II 给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k. / ...

  7. [Offer收割] 编程练习赛63

    题目1 : 命名 时间限制:5000ms 单点时限:1000ms 内存限制:256MB 描述 有两个公司想要合并,第一个公司的名字是一个字符串S,第二个公司的名字是一个字符串T. 合并后的新公司是这样 ...

  8. 自制操作系统Antz(12)——承上启下

    我已经规范了系统代码风格,类似于按照linux分包,把各部分功能区分开了 Antz系统更新地址 Linux内核源码分析地址 Github项目地址 在之前的工作中,AntzOS已经从单调的界面,变得逐渐 ...

  9. 函数def

    函数:把执行一定功能的动作封装到一起>>> def 函数名(形参)      通过一个    函数名(实参)         去调用它,传参来执行功能.动作,输出结果 .定义:def ...

  10. SAP 查询分析器,查询报表自动生成,SQL查询测试实现说明(转)

    在日常的SAP开发和应用中,经常需要通过查询SAP数据表来处理日常业务,比如:数据对账.报表SQL测试.SAP查询功能开发等.通过开发SAP查询分析器,SAP实施和开发人员,可以在较短的时间内查询到需 ...