python - 无法理解 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')
,为什么它在决赛中是否有新行?
解决方案
我认为您可能会使事情过于复杂。实际上,您在阅读时删除'\n'
了所有line.rstrip('\n')
内容。只需在写入时将其S.pop() + '\n'
插入每一行。否则,您将得到一条长线。
'\n'
有些文件末尾没有 a 。整个过程建议在倒写时在最后一行和倒数第二行之间插入一个换行符,否则这两个会合并。
推荐阅读
- r - Inner join with two reactive dataframes shiny
- tensorflow - 如何在谷歌云平台上使用带有 tf.estimator 的 datalab 的 tensorboard 调试器
- grails - 将 grails 与 hashcorp vault 集成
- windows - 删除多个对其具有保护的 AD OU
- typescript - 如何使用 typesafe-actions 调度异步操作?
- javascript - jQuery - Ajax 异步不起作用?
- getstream-io - 对于 getstream.io,评论/点赞的最佳活动模型是什么?
- git - 为什么 GitHub 在比较两个相同的分支时会显示变化?
- angular - 如何在 Angular 6 应用程序的索引页面中隐藏/显示按钮?
- javascript - 简单的重构会扼杀反应性