python逐行读取文件会读取空白行吗

Python021

python逐行读取文件会读取空白行吗,第1张

python逐行读取文件会读取空白行。

逐行读取时每行后面会打印一个空白行,因为文件中每行的末尾都有一个看不见的换行符,而函数调用print()也会加上一个换行符,因此每行末尾都有两个换行符。

Python由荷兰数学和计算机科学研究学会的吉多·范罗苏姆于1990年代初设计,作为一门叫做ABC语言的替代品。Python提供了高效的高级数据结构,还能简单有效地面向对象编程。

python实现去掉空行

# coding = utf-8

def clearBlankLine():

file1 = open('text1.txt', 'r', encoding='utf-8') # 要去掉空行的文件

file2 = open('text2.txt', 'w', encoding='utf-8') # 生成没有空行的文件

try:

for line in file1.readlines():

if line == '\n':

line = line.strip("\n")

file2.write(line)

finally:

file1.close()

file2.close()

if __name__ == '__main__':

clearBlankLine()