我用python3编写了一个程序来编辑文本文件,并将编辑后的版本输出到一个新的文本文件中。但是新文件中有我不能拥有的空白行,我也不知道如何删除它们。在
提前谢谢。在
newData = ""
i=0
run=1
j=0
k=1
seqFile = open('temp100.txt', 'r')
seqData = seqFile.readlines()
while i < 26:
sLine = seqData[j]
editLine = seqData[k]
tempLine = editLine[0:20]
newLine = editLine.replace(editLine, tempLine)
newData = newData+sLine+'\n'+newLine+'\n'
i=i+1
j=j+2
k=k+2
run=run+1
seqFile.close()
new100 = open("new100a.fastq", "w")
sys.stdout = new100
print(newData)
sLine
已包含新行。^如果editLine
较短或等于20个字符,则{newData = newData+sLine+'\n'+newLine+'\n'
到
newData = newData+sLine+newLine
在
editLine
超过20个字符的情况下,当您执行tempLine = editLine[0:20]
操作时,后面的换行符将被截断,您将需要在newData
后面追加一个新行。在根据pythondocumentation on readline(由readlines使用),每行中都会保留尾随的新行:
一般来说,当您遇到意外行为时,通过打印变量的值,通常可以在调试程序时获得很长的路要走。例如,用
print repr(sLine)
打印sLine
会显示其中有一个尾随的换行符。在问题出在这条线上:
sLine
已经包含换行符,因此您应该删除第一个'\n'。如果newLine
的长度小于20,那么newLine
也包含新行。在另一种情况下,您应该向它添加换行符。在试试这个:
^{pr2}$相关问题 更多 >
编程相关推荐