python - 查找并写入列中的下一个空白单元格
问题描述
我需要找到并写入下一个空白单元格。
import csv
with open(r'C:\\filepath\file.txt', 'r') as input_file:
reader = csv.reader(input_file)
with open (r'C:\filepath\file.csv', 'a', newline = '') as output_file:
writer = csv.writer(output_file)
for row in reader:
content = [i.split('~') for i in row]
for row1 in content:
con = [len(k.split('*')) for k in row1]
conn = [m.split('*') for m in row1]
for b in conn:
if con[0] > 4:
if (b[0] == 'NM1' and b[1] == '82' and b[2] == '1' ):
writer.writerow([b[3]] + [b[4]])
print ( b[3] + b[4] )
elif (b[0] == 'GS' ):
writer.writerow(['','','',b[2]])
print(b[2])
寻求获得如上图所示的输出。现在在第一行中只有“App1”正在打印,然后在第二行中打印名称等。我正在使用的输入文件如下所示。:
ISA*16* 00 0*T*>~
GS*IN*APP1*0999~
HPT*1*2~ SE*21*0001~
GE*1*145~
NM1*82*1*Tiger1a*Test1*K****~
NM1*82*1*Lion1a*Test2*K****~
NM1*82*1*Elephant1a*Test3*K****~
ISA*16* 00 0*T*>~
GS*IN*APP2*0999~
HPT*1*2~ SE*21*0001~
GE*1*145~
NM1*82*1*Tiger1a*Test4*K****~
ISA*16* 00 0*T*>~
GS*IN*APP1*0999~
HPT*1*2~
SE*21*0001~
GE*1*145~
NM1*82*1*Tiger1a*Test4*K****~
NM1*82*1*Lion1a*Test5*K****~
NM1*82*1*Elephant1a*Test6*K****~
ISA*16* 00 0*T*>~
GS*IN*APP10999~
HPT*1*2~
SE*21*0001~
GE*1*145~
NM1*82*1*Tiger1a*Test7*K****~
[![在此处输入图像描述][2]][2]
解决方案
好的,我假设您有一个输入文件,其中'~'
是记录分隔符和'*'
字段分隔符。由于 csv 模块仅处理行,因此我将首先使用生成器将输入文件拆分为~
.
然后我会提供 2 个列表,一个以记录开头NM1*82*1
并包含以下 2 个字段的列表,一个以GS
包含一个字段开头的记录。
最后,我会将第二个列表的每一行添加到第一个列表的相应行中。
代码可以是:
def splitter(fd, sep):
"""Splits fd (assumed to be an input file object) on sep ignoring end of lines"""
last = ""
for line in fd:
lines = line.strip().split(sep)
lines[0] = last + lines[0]
last = lines.pop()
for l in lines:
yield(l.strip())
if last != "":
yield last.strip()
return
with open(r'C:\\filepath\file.txt', 'r') as input_file, \
open (r'C:\filepath\file.csv', 'a', newline = '') as output_file:
rd = csv.reader(splitter(input_file, '~'), delimiter='*')
wr = csv.writer(output_file)
ls1 = []
ls2 = []
for b in rd:
if b[0] == 'NM1' and b[1] == '82' and b[2] == '1':
ls1.append([b[3], b[4]])
elif b[0] == 'GS':
ls2.append(b[2])
for i, b in enumerate(ls2):
ls1[i].append(b)
wr.writerows(ls1)
我得到:
Tiger1a,Test1,APP1
Lion1a,Test2,APP2
Elephant1a,Test3,APP1
Tiger1a,Test4,APP10999
Tiger1a,Test4
Lion1a,Test5
Elephant1a,Test6
Tiger1a,Test7
推荐阅读
- django - view.py 中的 Django Form If 条件与 2 个实例
- laravel - Vagrant Up VAB:警告:远程连接断开。重试
- typescript - 在 Typescript 的嵌套箭头函数中返回响应的最佳方法
- javascript - 如何在 requestPictureInPicture 中播放多个视频?
- python - get_absolute_url() 缺少 1 个必需的位置参数:'self'
- python - ODBC for SQL Server in Python
- java - Is it possible to test a java-based CRUD without using Spring Boot JPA?
- php - PHP mysql按键排序JSON数据
- html - Shopify - 公告栏更新
- c++ - 为什么这两个简单的循环都不是无限的?