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

时间:2018-05-23 19:07:33

标签: python stack strip

我正在读一本名为 Python中的数据结构和算法的书。不幸的是,我现在被困住了。

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

您可以忽略ArrayStack类,因为它只是构建堆栈。 请参阅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总是会抓住“文件末尾没有换行符”。

但为什么会这样呢?

其他行很好,但为什么只有最后一行有这个问题呢?

如果'\n'.rstrip('\n')删除,为什么在决赛中是否有新行呢?

2 个答案:

答案 0 :(得分:0)

我认为你可能会使事情过于复杂。有效地,您在阅读时会删除'\n'的每个line.rstrip('\n')S.pop() + '\n'只需在写入时为每一行插入此内容。否则你最终会得到一条长线。

有些文件最后没有'\n'。建议整个过程在反向写入时在最后一行和最后一行之间插入换行符,否则这两行会合并。

答案 1 :(得分:0)

换行符分隔行。根据定义,除了最后一行之外的所有行都必须有换行符...因为这就是使它们行的原因。最后一行可能有也可能没有换行符。你知道它到达行的结尾只是因为你到达了文件的末尾。

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

通过剥离换行符并在最后手动添加它们来修复它。 rstrip检查最后是否有换行符并将其删除。

相关问题