Python处理文本换行符

源文件每行后面都有回车,所以用下面输出时,中间会多了一行

try:
    with open("F:\hjt.txt" ) as f :
        for line in f:
            print(line)
except FileNotFoundError:
    print("读取文件出错")

 

有两种方法处理:

1.print后面带 end='',表示不换行

try:
    with open("F:\hjt.txt" ) as f :
        for line in f:
            print(line,end='')
except FileNotFoundError:
    print("读取文件出错")

2.用strip()函数去掉每一行的换行符

try:
    with open("F:\hjt.txt" ) as f :
        for line in f:
            line = line.strip('
')
            print(line)
except FileNotFoundError:
    print("读取文件出错")

原文地址:https://www.cnblogs.com/hjhsysu/p/5748776.html