[python]《Python编程快速上手:让繁琐工作自动化》学习笔记5
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的更多相关文章
- python学习笔记整理——字典
python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...
- VS2013中Python学习笔记[Django Web的第一个网页]
前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...
- python学习笔记之module && package
个人总结: import module,module就是文件名,导入那个python文件 import package,package就是一个文件夹,导入的文件夹下有一个__init__.py的文件, ...
- python学习笔记(六)文件夹遍历,异常处理
python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...
- python学习笔记--Django入门四 管理站点--二
接上一节 python学习笔记--Django入门四 管理站点 设置字段可选 编辑Book模块在email字段上加上blank=True,指定email字段为可选,代码如下: class Autho ...
- python学习笔记--Django入门0 安装dangjo
经过这几天的折腾,经历了Django的各种报错,翻译的内容虽然不错,但是与实际的版本有差别,会出现各种奇葩的错误.现在终于找到了解决方法:查看英文原版内容:http://djangobook.com/ ...
- python学习笔记(一)元组,序列,字典
python学习笔记(一)元组,序列,字典
- Pythoner | 你像从前一样的Python学习笔记
Pythoner | 你像从前一样的Python学习笔记 Pythoner
- OpenCV之Python学习笔记
OpenCV之Python学习笔记 直都在用Python+OpenCV做一些算法的原型.本来想留下发布一些文章的,可是整理一下就有点无奈了,都是写零散不成系统的小片段.现在看 到一本国外的新书< ...
- python学习笔记(五岁以下儿童)深深浅浅的副本复印件,文件和文件夹
python学习笔记(五岁以下儿童) 深拷贝-浅拷贝 浅拷贝就是对引用的拷贝(仅仅拷贝父对象) 深拷贝就是对对象的资源拷贝 普通的复制,仅仅是添加了一个指向同一个地址空间的"标签" ...
随机推荐
- ASP.NET Core :缓存系列(四):内存缓存 MemoryCache
System.Runtime.Caching/MemoryCache ICacheEntry 接口中的属性:具体设置过期时间 可以参考:微软文档ICacheEntry 接口 缓存基本使用 (一) 绝对 ...
- 1.2.2 musl pwn
1.2.2 musl pwn 几个结构 __malloc_context(与glibc中的main_arena类似) struct malloc_context { uint64_t secret; ...
- ansible使用临时命令通过模块来执行任务
使用临时命令通过模块来执行任务 一.查看系统上安装的所有模块 ansible-doc -l 查看ping模块帮助文档 ansible-doc ping 1.ansible模块 文件模块: copy:将 ...
- Linux软件安装方式 - Tarball&RPM&YUM
软件安装 简介 概念详解 # 概念详解 - 开放源码: 程序码, 写给人类看的程序语言, 但机器并不认识, 所以无法执行; - 编译器: 将程序码转译成为机器看的懂得语言, 就类似翻译者的角色; - ...
- 四、Pod 介绍
一.什么是 Pod Pod 是 kubernetes 集群中最小的部署和管理的基本单元,协同寻址,协同调度. Pod 是一个或多个容器的集合,是一个或一组服务(进程)的抽象集合. Pod 中可以 ...
- Seata 1.5.2 源码学习
文章有点长,我决定用半个小时来给您分享~ 基于Seata 1.5.2,项目中用 seata-spring-boot-starter 1. SeataDataSourceAutoConfiguratio ...
- Idea在windows和mac中的一些快捷指令
从 Windows 过度到 Mac 必备快捷键对照表 Mac 键盘符号说明 ⌘ == Command ⇧ == Shift ⇪ == Caps Lock ⌥ == Option ⌃ == Contro ...
- js和jquery页面初始化加载函数的方法及顺序
运行下面代码.弹出A.B.C.D.E的顺序:A=B=C>D=E. <html> <head> <title>首页</title> <scri ...
- Vue 基础学习总结
介绍 Vue.js 中文文档地址:https://cn.vuejs.org/guide/introduction.html#what-is-vue Vue.js 是什么 Vue (读音 /vjuː/, ...
- 13、设计一个函数process,在你调用他的时候,每次实现不同的功能,输入a,b两个数, 第一次调用时找出a,b中的最大者。 第二次找出最小者,,第三次求两个数的和。
/* 设计一个函数process,在你调用他的时候,每次实现不同的功能,输入a,b两个数, 第一次调用时找出a,b中的最大者. 第二次找出最小者,,第三次求两个数的和. */ #include < ...