删除文本文件输出python3中的空行

2024-09-26 22:51:21 发布

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

我用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)

Tags: run程序版本编辑newlineopenpython3文本文件
2条回答

sLine已包含新行。^如果editLine较短或等于20个字符,则{}也将包含一个换行符。你可以改变

newData = newData+sLine+'\n'+newLine+'\n'

newData = newData+sLine+newLine

editLine超过20个字符的情况下,当您执行tempLine = editLine[0:20]操作时,后面的换行符将被截断,您将需要在newData后面追加一个新行。在

根据pythondocumentation on readline(由readlines使用),每行中都会保留尾随的新行:

Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). [6] If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. When size is not 0, an empty string is returned only when EOF is encountered immediately.

一般来说,当您遇到意外行为时,通过打印变量的值,通常可以在调试程序时获得很长的路要走。例如,用print repr(sLine)打印sLine会显示其中有一个尾随的换行符。在

问题出在这条线上:

newData = newData+sLine+'\n'+newLine+'\n'

sLine已经包含换行符,因此您应该删除第一个'\n'。如果newLine的长度小于20,那么newLine也包含新行。在另一种情况下,您应该向它添加换行符。在

试试这个:

^{pr2}$

相关问题 更多 >

    热门问题