避免将'\n'写入python中文件的最后一行

2024-05-16 09:04:07 发布

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

我正在将多行写入一个新文件(可能高达几GB),如下所示:

for item in record:
    output_pass.write('%s\n' %item)

但是,由于上一条记录的“\n”,我得到了一个空行,例如:

文件的开头

record111111

reocrd222222

record333333

---a blank line---

文件结尾

由于我的文件很大,我不想再读取该文件。那么,有什么简单的方法可以防止这种情况发生,或者从文件中删除最后一个“\n”?

我的解决方案:

谢谢你的帮助!

我想我不会将整个文件加载到内存中,因为它可能会变得非常大。

实际上,我通过先写第一条记录,然后在循环中写下其余的行来解决这个问题。我把“\n”放在前面,这样它就不会出现在最后一行。

但乔纳森是对的。实际上,我现在对最后一行的“\n”有问题,主要是我的强迫症。

这是我的代码:

rec_first = parser_fastq.next() #This is just an iterator of my file
output.write('%s' %('>'+rec_first[0].strip('@')))
output.write('\n%s' %(rec_first[1])) #I put '\n' in the front

count = 1

#Write the rest of lines
for rec_fastq in parser_fastq:
    output.write('\n%s' %('>'+rec_fastq[0].strip('@')))
    output.write('\n%s' %(rec_fastq[1]))
    count += 1
    print 'Extracting %ith record in %s ...' %(count, fastq_name) + '\b'*100,

output.close()

打印'\n%i记录已写入%s'%(count,fasta\u name)


Tags: 文件ofinparserforoutputcount记录