繁体   English   中英

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

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

我正在读一本书《 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')删除,为什么在最后是否有新行很重要?

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

某些文件的末尾没有'\\n' 建议以整个过程在反向写入时在最后一行和倒数第二行之间插入换行符,否则这两部分将合并。

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

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

它通过删除换行符并在末尾手动添加来解决。 rstrip检查rstrip是否有换行符并将其删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM