Python 查找并写入列中的下一个空白单元格
我需要找到下一个空白单元格并给它写信Python 查找并写入列中的下一个空白单元格,python,python-3.x,csv,Python,Python 3.x,Csv,我需要找到下一个空白单元格并给它写信 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) f
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****~
[![enter image description here][2][2]尝试将文件读入单独的字典,并将行号作为键。然后可以使用zip函数同时遍历这两个词典
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
sentinel = object()
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield tuple(result)
这里的更多信息:好的,我假设您有一个输入文件,其中
'~'
是记录分隔符,'*'
是字段分隔符。由于csv模块只处理行,我将首先使用生成器在~
上拆分输入文件
然后我将提供两个列表,一个以NM1*82*1
开头的记录包含以下两个字段的列表,一个以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,测试3,附录1
老虎1A,测试4,APP10999
老虎1A,测试4
莱昂娜,测试5
Elephant1a,测试6
老虎1A,测试7
由于格式的原因,很难说出你到底在问什么。你能稍微整理一下,让你的输入和输出更清晰吗?@chriscomments删除所有格式。您可以编辑您的问题。您提到的输入(相当奇怪)是原始csv文件的产品吗?或者,~
和*
分开的数据是您必须处理的原始数据吗?对于前者,您可以使用例如以更有效的方式解析输入。