一、使用场景
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