I've tried several ways to append a string to a line being written to a file when reading from another file (as well as in place using fileinput). I'm definitely missing something but trying different approaches for a few hours has not fixed the problem.
The latest approach is below, which still results in the imagelist being on a new line after the datarow where the goal is to output them to a single line.
for datarow in oldfile:
rowcols = datarow.split('|')
imagelist = []
image_seed = rowcols[headers.index('Group ID')]+'_'+rowcols[headers.index('Case ID')]+'_'+rowcols[headers.index('Contact ID')]
if isfirstrow:
newfile.write(headerrow)
isfirstrow = False
else:
for imagename in imagefiles:
if image_seed in imagename:
imagelist.append(os.path.basename(imagename))
if len(imagelist) > 0:
imagelist.insert(0, datarow)
newfile.write('|'.join(imagelist)+'\n')
else: newfile.write(datarow)
Thanks in advance for you input!
You probably have some remaining '\n' either in front of your 1st item of your imagelist or after datarow. Unfortunately you don't show how you read oldfile.
Solution: clean '\n' from it:
imagelist.insert(0, datarow.rstrip('\n')) # rstrip for clean on end
newfile.write('|'.join(x.strip('\n') for x in imagelist)+'\n') # strip: clean both ends
Maybe you should give this a read:
How to debug small programs (#5)
You might also need to clean up
else: newfile.write(datarow.rstrip('\n')+'\n') # make it consistently have a \n