python处理excel:按照某一种特殊符号拆分为多行

一、使用场景

111.png

二、代码

#!/usr/bin/env python3
# _._ coding: utf-8 _._

import csv
import optparse
import os

if __name__ == '__main__':
    parser = optparse.OptionParser()
    parser.add_option('-f', '--file', dest='file', help='CSV文件路径')
    parser.add_option('-i', '--index', dest='index', help='拆分列索引,从0开始', type=int)
    parser.add_option('-s', '--separator', dest='sep', help='拆分分隔符')

    # 解析命令行参数
    options, args = parser.parse_args()
    if not options.file or not options.sep:
        parser.print_help()

        exit(0)

    # 处理数据
    name, ext = os.path.basename(options.file).split('.')
    if 'csv' != ext:
        print('必须提供一个CSV文件')

    with open(options.file, 'r') as in_file:
        filename = "{}-1.csv".format(name)
        with open(filename, 'w') as out_file:
            writer = csv.writer(out_file)

            reader = csv.reader(in_file)
            for row in reader:
                # 空行忽略
                if '' == ''.join(row).strip():
                    continue

                # 索引溢出
                if options.index >= len(row):
                    continue

                values = row[options.index]
                for value in values.split(options.sep):
                    # 忽略空值
                    if '' == value.strip():
                        continue

                    row[options.index] = value

                    writer.writerow(row)

三、使用方法

# 打开终端
admin@admindeMacBook-Pro-3 ~ %  ./script/split-data-column.py -f test001.csv -i 0 -s '、'
结果展示.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容