无法理解 rstrip('\n') 发生了什么

Cannot understand what is going on with rstrip('\n')

我正在读一本名为 Data Structure And Algorithm In Python 的书。不幸的是,我现在卡住了。

它是关于使用堆栈以相反的顺序重写文件中的行。

您可以忽略 ArrayStack class,因为它只是用来构建堆栈的。 请参阅 reverse_file 函数。

''' Thanks Martineau for editing this to transform bunch of lines to code!'''
class Empty(Exception):
    ''' Error attempting to access an element from an empty container.
    '''
    pass


class ArrayStack:
''' LIFO Stack implementation using a Python list as underlying storage.
'''
    def __init__(self):
        ''' Create an empty stack.
        '''
        self._data = []  # nonpublic list instance

    def __len__(self):
        ''' Return the number of elements in the stack.
        '''
        return len(self._data)

    def is_empty(self):
        ''' Return True if the stack is empty.
        '''
        return len(self._data) == 0

    def push(self, e):
        ''' Add element e to the top of the stack.
        '''
        self._data.append(e)  # new item stored at end of list

    def top(self):
        ''' Return (but do not remove) the element at the top of the stack

        Raise Empty exception if the stack is empty.
        '''
        if self.is_empty():
            raise Empty('Stack is empty.')
        return self._data[-1]  # the last item in the list

    def pop(self):
        ''' Remove and return the element from the top of the stack (i.e, LIFO)

        Raise Empty exception if the stack is empty.
        '''
        if self.is_empty():
            raise Empty('Stack is empty.')
        return self._data.pop()


def reverse_file(filename):
    ''' Overwrite given file with its contents line-by-line reversed. '''
    S = ArrayStack()
    original = open(filename)
    for line in original:
        S.push(line.rstrip('\n'))
    original.close()  # we will re-insert newlines when writing.

    # now we overwrite with contents in LIFO order.
    output = open(filename, 'w')
    while not S.is_empty():
        output.write(S.pop() + '\n')
    output.close()


if __name__ == '__main__':
    reverse_file('6.3.text')

书上说我们必须使用.rstrip('\n')方法,否则原始文件的最后一行后面跟着(没有换行符)倒数第二行,这是一种特殊情况,文件没有最后的空白行 - 如您所知,pep8 总是用 "no newline at end of file".

抓住您

但为什么会这样?

其他行没问题,为什么只有最后一行有问题?

如果'\n'会被.rstrip('\n')删除,那么最后一行是否换行有什么关系呢?

我认为你可能把事情复杂化了。实际上,您在阅读时用 line.rstrip('\n') 删除了每个 '\n'S.pop() + '\n' 只是在写入时为每一行插入它。否则你最终会得到一条长线。

有些文件末尾没有 '\n'。整个过程建议在倒写时在最后一行和倒数第二行之间插入一个换行符,否则两者会合并。

换行符分隔行。根据定义,除了最后一行之外的所有行都必须有换行符……因为这就是它们的行。最后一行可能有也可能没有换行符。您仅通过到达文件末尾就知道它是该行的末尾。

想想一个更简单的算法。您将这些行读入列表,反转并写入列表的项目。由于反转,最后一行现在是第一行。如果它没有换行符,当你写第一项和第二项时成为第一行。

通过删除换行符并在末尾手动添加它们来修复它。 rstrip 检查末尾是否有换行符并删除。