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. Oracle中hex和raw的相互转换

    可以参考以下语句: select hextoraw(rawtohex('你好')) from dual select utl_raw.cast_to_varchar2(hextoraw('E4BDA0 ...

  2. Godot-富文本

    作用:添加链接(比如赞助网站,或者相关站点什么的) 效果如下: (引用Godot官网) Introduction RichTextLabel allows the display of complex ...

  3. django 后端反向生成url

    导入模块 from django.core.urlresolvers import reverse reverse() reverse(viewname, urlconf=None, args=Non ...

  4. Maven不能下载SNAPSHOT包但是能下载RELEASE包的解决办法

    在使用过程中,Maven默认配置是不能下载SNAPSHOT包的,这是基于一种代码稳定性进行考量得出的结论.引入SNAPSHOT包最大的问题就是,由于SNAPSHOT允许重复上传,所以引用一个这样的包开 ...

  5. html中div标签怎么用?

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

  6. 解决ssh连接问题1

    某天服务器A与B,互相ping没问题,telnet 22端口没问题 ssh -v a@10.80.97.241 OpenSSH_6.6.1, OpenSSL 1.0.1k-fips 8 Jan 201 ...

  7. 遍历table明细是否为空

    //循环遍历 <tbody id="linedata2">,获取每行值对比 $("#linedata2 tr").each(function(i,n ...

  8. vue-cli —— 局部修改Element样式

    最近在做vue项目时用到了Element,发现这玩意儿用起来很舒服,很新颖,上手也很快,而且效果足够酷炫.但是后面发现一个很大的问题,那就是Element的样式有限,这极大地限制了项目的应用广度,所以 ...

  9. delphi idhttp post 普通提交乱码处理

    var IdHTTP1:TIdHTTP; postStream : TStringStream; Wstr:WideString; res:WideString; begin IdHTTP1 := T ...

  10. 新疆大学ACM-ICPC程序设计竞赛五月月赛(同步赛)A Red Rover

    题目链接 大概意思就是,找出一个字串,将其所有出现的地方替换成一个字母M后的长度len1,然后再加上这个字串的长度t_len得到一个新的长度len,求这个len最小等于多少. 当然,也可以不找这个串, ...