1. 处理CSV文件笔记(第14章) (代码下载)

本文主要在python下介绍CSV文件,CSV 表示“Comma-Separated Values(逗号分隔的值)”,CSV文件是简化的电子表格,保存为纯文本文件。CSV 文件中的每行代表电子表格中的一行,逗号分割了该行中的单元格。Python 的csv模块让解析CSV 文件变得容易。CSV模块为Python自带库。常用函数如下:

函数 用途 备注
exampleFile = open(path) 打开文件,返回file文件 非csv模块中的函数,但可以用于打开csv文件
csv.reader(exampleFile) 将file文件转换为一个Reader对象 不能直接将文件名字符串传递给csv.reader()函数
exampleData = list(exampleReader) 在Reader 对象上应用list()函数,将返回一个csv文件内容列表 非csv模块中的函数
outputFile = open(‘output.csv’, ‘w’, newline=’’) open()并传入’w’,以写模式打开一个文件 如果忘记设置newline关键字参数为空字符,output.csv中的行距将有两倍
outputWriter.writerow[lists] 将lists写入csv文件中
csv.writer(csvFile, delimiter=’\t’) 将csv文件中的分隔符改为’\t’
csv.writer(csvFile, lineterminator=’\n\n’) 将csv文件中的行终止字符改为’\n\n’

2. 项目练习

2.1 项目:从CSV 文件中删除表头

读取当前工作目录中所有扩展名为.csv 的文件,除掉第一行的内容重新写入同名的文件。用新的、无表头的内容替换CSV 文件的旧内容。

import csv
import os # 创建文件夹,exist_ok=True表示文件夹如果存在则不报错
os.makedirs('headerRemoved', exist_ok=True)
# Loop through every file in the current working directory.
# 查找本地所有文件
for csvFilename in os.listdir('.'):
if not csvFilename.endswith('.csv'):
# skip non-csv files 跳过不是csv文件
continue
print('Removing header from ' + csvFilename + '...') # Read the CSV file in (skipping first row). 读取文件跳过第一行
csvRows = []
csvFileObj = open(csvFilename)
readerObj = csv.reader(csvFileObj)
# 读取每一行
for row in readerObj:
# 跳过第一行
# readerObj.line_num 表示行号从1开始
if readerObj.line_num == 1:
# skip first row
continue
# 保存数据
csvRows.append(row)
csvFileObj.close() # Write out the CSV file. 写文件
csvFileObj = open(os.path.join(
'headerRemoved', csvFilename), 'w', newline='')
csvWriter = csv.writer(csvFileObj)
for row in csvRows:
csvWriter.writerow(row)
csvFileObj.close()
Removing header from example.csv...

2.2 Excel 到CSV 的转换程序

将多个excel文件保存csv文件。一个Excel 文件可能包含多个工作表,必须为每个表创建一个CSV 文件。CSV文件的文件名应该是<Excel 文件名>_<表标题>.csv,其中<Excel 文件名>是没有扩展名的Excel 文件名(例如’spam_data’,而不是’spam_data.xlsx’),<表标题>是Worksheet 对象的title 变量中的字符串。

import openpyxl
import os
import csv inputPath = './excelSpreadsheets'
outputPath = './outputSheets' # 创建文件夹
os.makedirs(outputPath, exist_ok=True)
for excelFile in os.listdir(inputPath):
# Skip non-xlsx files, load the workbook object.
# 跳过不是xlsx的文件
if not excelFile.endswith('xlsx'):
continue
# 输入文件
inputFilePath = os.path.join(inputPath, excelFile)
# 打开xlsx文件
wb = openpyxl.load_workbook(inputFilePath)
# 获得当前文件sheetName
for sheetName in wb.sheetnames:
# 设置文件
csvFileName = excelFile.split('.')[0]+'_'+sheetName+'.csv'
csvFile = open(os.path.join(outputPath, csvFileName), 'w', newline='')
print("current file is: {}".format(csvFileName))
# 写csv文件
outputWriter = csv.writer(csvFile)
sheet = wb[sheetName] # 遍历每一行数据
for rowNum in range(1, sheet.max_row+1):
# 保存每一行数据
rowData = []
for colNum in range(1, sheet.max_column+1):
# 保存每一列数据
rowData.append(sheet.cell(row=rowNum, column=colNum).value)
# 写入一行数据
outputWriter.writerow(rowData)
csvFile.close()
current file is: spreadsheet-A_Sheet.csv
current file is: spreadsheet-B_Sheet.csv
current file is: spreadsheet-C_Sheet.csv
current file is: spreadsheet-D_Sheet.csv
current file is: spreadsheet-E_Sheet.csv
current file is: spreadsheet-F_Sheet.csv
current file is: spreadsheet-G_Sheet.csv
current file is: spreadsheet-H_Sheet.csv
current file is: spreadsheet-I_Sheet.csv
current file is: spreadsheet-J_Sheet.csv
current file is: spreadsheet-K_Sheet.csv
current file is: spreadsheet-L_Sheet.csv
current file is: spreadsheet-M_Sheet.csv
current file is: spreadsheet-N_Sheet.csv
current file is: spreadsheet-O_Sheet.csv
current file is: spreadsheet-P_Sheet.csv
current file is: spreadsheet-Q_Sheet.csv
current file is: spreadsheet-R_Sheet.csv
current file is: spreadsheet-S_Sheet.csv
current file is: spreadsheet-T_Sheet.csv
current file is: spreadsheet-U_Sheet.csv
current file is: spreadsheet-V_Sheet.csv
current file is: spreadsheet-W_Sheet.csv
current file is: spreadsheet-X_Sheet.csv
current file is: spreadsheet-Y_Sheet.csv
current file is: spreadsheet-Z_Sheet.csv

[python]《Python编程快速上手:让繁琐工作自动化》学习笔记5的更多相关文章

  1. python学习笔记整理——字典

    python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...

  2. VS2013中Python学习笔记[Django Web的第一个网页]

    前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...

  3. python学习笔记之module && package

    个人总结: import module,module就是文件名,导入那个python文件 import package,package就是一个文件夹,导入的文件夹下有一个__init__.py的文件, ...

  4. python学习笔记(六)文件夹遍历,异常处理

    python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...

  5. python学习笔记--Django入门四 管理站点--二

    接上一节  python学习笔记--Django入门四 管理站点 设置字段可选 编辑Book模块在email字段上加上blank=True,指定email字段为可选,代码如下: class Autho ...

  6. python学习笔记--Django入门0 安装dangjo

    经过这几天的折腾,经历了Django的各种报错,翻译的内容虽然不错,但是与实际的版本有差别,会出现各种奇葩的错误.现在终于找到了解决方法:查看英文原版内容:http://djangobook.com/ ...

  7. python学习笔记(一)元组,序列,字典

    python学习笔记(一)元组,序列,字典

  8. Pythoner | 你像从前一样的Python学习笔记

    Pythoner | 你像从前一样的Python学习笔记 Pythoner

  9. OpenCV之Python学习笔记

    OpenCV之Python学习笔记 直都在用Python+OpenCV做一些算法的原型.本来想留下发布一些文章的,可是整理一下就有点无奈了,都是写零散不成系统的小片段.现在看 到一本国外的新书< ...

  10. python学习笔记(五岁以下儿童)深深浅浅的副本复印件,文件和文件夹

    python学习笔记(五岁以下儿童) 深拷贝-浅拷贝 浅拷贝就是对引用的拷贝(仅仅拷贝父对象) 深拷贝就是对对象的资源拷贝 普通的复制,仅仅是添加了一个指向同一个地址空间的"标签" ...

随机推荐

  1. 从 Paxos 到 ZooKeeper

    分布式一致性 分布式文件系统.缓存系统和数据库等大型分布式存储系统中,分布式一致性都是一个重要的问题. 什么是分布式一致性?分布式一致性分为哪些类型?分布式系统达到一致性后将会是一个什么样的状态? 如 ...

  2. 🔥支持 Java 19 的轻量级应用开发框架,Solon v1.10.4 发布

    Java 轻量级应用开发框架.可用来快速开发 Java 应用项目,主框架仅 0.1 MB. 相对于 Spring Boot 和 Spring Cloud 的项目: 启动快 5 - 10 倍. (更快) ...

  3. 如何编写 Pipeline 脚本

    前言 Pipeline 编写较为麻烦,为此,DataKit 中内置了简单的调试工具,用以辅助大家来编写 Pipeline 脚本. 调试 grok 和 pipeline 指定 pipeline 脚本名称 ...

  4. 解决console控制台反复打印“WebSocket connection to ws://localhost:9528/sockjs-node/107/uadaszgz.websocket failed:Invalid frame header

    element-admin-vue 项目console台一直报websocket连接失败 解决办法 1.vue.config.js中配置devServer.proxy的ws为false  (我没成功) ...

  5. .net core-利用PdfSharpCore和SkiaSharp.QrCode 添加PDF二维码页眉

    前序 由于去年的一个项目需要在PDF 添加公司二维码 ,当时在网上找了很多操作PDF方案,第一种Aspose.PDF,很遗憾 Aspose.PDF 有添加版权的背景还是页脚我忘记了,不适合公司项目,最 ...

  6. 一文理解Cookie、Session

    一文理解Cookie.Session 1.什么是会话 用户打开浏览器,点击多个超链接,访问服务器的多个web资源,然后关闭浏览器,整个过程就称为一个会话: HTTP 是无状态,有会话的 HTTP 是无 ...

  7. Mysql综合实验2-LAMP+MHA+MYcat分库

    实验目标: 1.搭建主从半同步+GTID复制 2.搭建MHA主服务器高可用 3.Mycat实现分库:wordpress库和shopxo库 4.客户通过域名可以访问到wordpress和shopxo 实 ...

  8. day19-web开发会话技术01

    WEB开发会话技术01 1.会话 Web开发中,用到的4种会话跟踪技术 - 博客园 (cnblogs.com) 会话的基本介绍 什么是会话? 会话可简单理解为:用户开一个浏览器,点击多个超链接,访问服 ...

  9. AArch32/AArch64系统级内存模型(三)

    1. 内存系统架构 1.1 系统级存储系统体系结构的形式   Armv8的a -profile体系结构包括一个虚拟内存系统体系结构(Virtual Memory System Architecture ...

  10. Spring校验器实例

    @size (min=3, max=20,message="用户名长度只能在3-20之间") @size (min=6, max=20,message="密码长度只能在6 ...