[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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值