我正在将多行内容写入新文件(可能达到几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' %(计数,fasta_name)
'\n'
字符结尾。 - martineau