Python读写csv小白指南
来源:互联网 发布:matlab2017a for mac 编辑:程序博客网 时间:2024/05/21 01:45
这个暑期用Python帮老板爬各种企业联系方式,感受到了csv文件格式深深的恶意,各种编码混乱搞得我这只小白焦头烂额,网上各路前辈的经验分享又不能100%切合自己的特殊场景。经历了无数次:打开文件乱码 – 换应用打开依然乱码 – 回炉重撸代码 – 终于正确打开之后,就有了这篇博文,也算是记录下折磨我死去活来的csv读写。
运行环境:
Windows 10 CMD
Python 2.7
简单说一下情况,有N个独立的utf-8编码的csv文件,其中的column数目、种类均不相同,目标是将所有csv文件合并成一个column统一的大csv,并且顺带做一些数据清洗。
思路如下:Python循环读取每一个csv,循环读取其中每一个row,数据清洗后,符合要求的写入新的csv。
一:
由于所有csv文件都用utf-8编码。因此在所有代码执行前,执行以下两行代码,虽然这个方法很不Python,但却是小白救星!
import sys reload(sys) sys.setdefaultencoding('utf-8')
二:
读取csv文件
import csv reader =csv.reader(open(input_file, 'rb'), delimiter=',') #input_file should be a string like "companies.csv" for row in reader: #row is a list containing elements in a single line of input file
三:
写入csv文件
import csvimport codecscsvfile = open(output_file,'wb') #output_file should be a string like "combined.csv"csvfile.write(codecs.BOM_UTF8)writer = csv.writer(csvfile, dialect='excel')writer.writerow(row) #row is a list of elements you want to write into a single line of output file
注意:即使有了第一点中的代码,csvfile.write(codecs.BOM_UTF8) 依然要写上,第一次没有加上这一行的时候,输出来是乱码。
四:
一个笨笨的查看txt或者csv文件编码的方法,Win10自带Notepad打开目标文件,左上角文件,另存为,弹出窗口右下角编码类型,所显示的就是文件的编码。图中文件为ANSI编码。
阅读全文
0 0
- Python读写csv小白指南
- Python读写csv文件
- python 读写 csv文件
- Python读写csv文件
- Python读写csv文件
- Python读写csv文件
- python 读写csv格式文件
- Python读写CSV数据
- Python读写csv文件
- Python读写csv文件
- Python--读写CSV文档
- Python读写csv文件
- Python读写csv文件
- Python--读写CSV文档
- Python读写csv文件
- Python读写csv文件
- python读写csv文件
- Python读写csv格式文件
- 一张图理解prototype、proto和constructor的三角关系
- 微信小程序把玩(三十七)location API
- hdu4258Covered Walkway(斜率)
- MVC简介及优缺点
- python—pandas中DataFrame类型数据操作函数
- Python读写csv小白指南
- Ignatius and the Princess IV
- Deeplearning4j源码研习(1): BP算法原理及源码实现
- POJ 1067 取石子游戏 经典威佐夫博弈
- 《Spring+Mybatis企业应用实战》学习-1~3章
- LinkedHashMap
- 数据结构串的基本操作及KMP算法
- 将Behavior插件和AStarPathFinding插件结合
- Example3.12 Solving the Gridworld