插入tex时在文件写入中添加新行

2024-06-12 03:46:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试了几种方法,在读取另一个文件时(以及使用fileinput时),将字符串附加到写入文件的行中。我肯定错过了一些东西,但尝试几个小时的不同方法并没有解决问题

下面是最新的方法,这仍然导致imagelist位于datarow之后的新行上,目标是将它们输出到一行

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)

提前感谢您的输入


Tags: 文件方法inimageidforindexif
1条回答
网友
1楼 · 发布于 2024-06-12 03:46:32

你可能在你的imagelist的第一项之前或之后有一些单词'\n'。不幸的是,你没有展示你是如何阅读的

溶液,从中清除'\n'

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

也许你应该读一下:How to debug small programs (#5)

你可能还需要清理一下

 else: newfile.write(datarow.rstrip('\n')+'\n')          # make it consistently have a \n

相关问题 更多 >