仅打印多行文件/字符串的最后一行

时间:2015-02-14 14:05:10

标签: python python-2.x line-endings

我在Stack Overflow上搜索了一下,偶然发现了不同的答案,但没有适合我的情况......

我有一个这样的map.txt文件:

+----------------------+                          
|                      |                          
|                      |                          
|                      |                          
|        test          |                          
|                      |                          
|                      |                          
|                      |                          
+------------------------------------------------+
|                      |                         |
|                      |                         |
|                      |                         |
|       Science        |       Bibliothek        |
|                      |                         |
|                      |                         |
|                      |                         |
+----------------------+-------------------------+

当我想用它打印时:

def display_map():
    s = open("map.txt").read()
    return s


print display_map()

它只是打印我:

 +----------------------+-------------------------+      

当我尝试使用与其他文本文件相同的方法时:

line 1
line 2
line 3

它完美无缺。

我做错了什么?

1 个答案:

答案 0 :(得分:6)

我猜这个文件使用CR (Carriage Return)字符(Ascii 13,或'\r')来换行;在Windows和Linux上,这只会将光标移回第1列,但不会将光标向下移动到新行的开头。

(当然这样的行终止符不会存在复制粘贴到Stack Overflow,这就是无法复制的原因。)

您可以使用repr调整字符串中的奇怪字符:

print(repr(read_map())

它将打印出所有特殊字符转义的字符串。


如果您在\r ed字符串中看到repr,则可以尝试这样做:

def read_map():
    with open('map.txt') as f:  # with ensures the file is closed properly
        return f.read().replace('\r', '\n') # replace \r with \n

或者为open提供U标记,以获取通用换行符,这会将'\r''\r\n''\n'全部转换为\n尽管有基本的操作系统惯例,但仍在阅读:

def read_map():
    with open('map.txt', 'rU') as f:
        return f.read()

相关问题