Python 生成尾部函数:反转文件中的行
我试图定义一个函数,输出文件中最后n行。除了fReverse中的前两行被连接在一起这一事实之外,下面的函数似乎大部分都起作用了,我不明白为什么 示例:(我尝试将它们放在块引号中而不是代码中,但这会破坏行格式) f= 弗雷弗斯=Python 生成尾部函数:反转文件中的行,python,python-2.7,Python,Python 2.7,我试图定义一个函数,输出文件中最后n行。除了fReverse中的前两行被连接在一起这一事实之外,下面的函数似乎大部分都起作用了,我不明白为什么 示例:(我尝试将它们放在块引号中而不是代码中,但这会破坏行格式) f= 弗雷弗斯= Like priceless treasures sinking in the sand.Beneath the touch of Time’s unerring hand, And see her might and granite wonders there, Dar
Like priceless treasures sinking in the sand.Beneath the touch of Time’s unerring hand,
And see her might and granite wonders there,
Darkly I gaze into the days ahead,
代码:
更容易使用
deque
此处:
要反转整个文件,请执行以下操作:
from collections import deque
with open('file') as fin:
reversed_lines = deque()
reversed_lines.extendleft(fin)
要显示最后的n
(但首先遍历所有行):
更容易使用
deque
此处:
要反转整个文件,请执行以下操作:
from collections import deque
with open('file') as fin:
reversed_lines = deque()
reversed_lines.extendleft(fin)
要显示最后的n
(但首先遍历所有行):
这是因为最后一行没有
\n
,它位于末尾;P
您可以尝试:
lines = reversed([l.strip()+'\n' for l in f])
fReverse.writelines(lines)
这是因为最后一行没有
\n
,它位于末尾;P
您可以尝试:
lines = reversed([l.strip()+'\n' for l in f])
fReverse.writelines(lines)
这里的问题是文件的最后一行没有以换行符结尾。因此
f.readlines()
将类似于以下内容(请注意,最终条目没有\n
):
因此,当您反向执行此操作时,您的第一行实际上不会写入\n
,并且fReverse.writelines()
不会自动添加一行结尾。要解决此问题,只需检查f.readlines()
中的最后一行是否以\n
结尾,并在必要时添加它:
def tail(filename, nlines):
'''Returns a list containing the last n lines of the file.'''
f = open(filename, 'r')
fReverse = open('output.txt', 'w')
lines = f.readlines()
if not lines[-1].endswith('\n'):
lines[-1] += '\n'
fReverse.writelines(reversed(lines))
fReverse.close()
f.close()
fReverse = open('output.txt', 'r')
listFile = []
for i in range(1,nlines+1):
listFile.append(fReverse.readline(),)
fReverse.close()
return listFile
这里的问题是文件的最后一行没有以换行符结尾。因此
f.readlines()
将类似于以下内容(请注意,最终条目没有\n
):
因此,当您反向执行此操作时,您的第一行实际上不会写入\n
,并且fReverse.writelines()
不会自动添加一行结尾。要解决此问题,只需检查f.readlines()
中的最后一行是否以\n
结尾,并在必要时添加它:
def tail(filename, nlines):
'''Returns a list containing the last n lines of the file.'''
f = open(filename, 'r')
fReverse = open('output.txt', 'w')
lines = f.readlines()
if not lines[-1].endswith('\n'):
lines[-1] += '\n'
fReverse.writelines(reversed(lines))
fReverse.close()
f.close()
fReverse = open('output.txt', 'r')
listFile = []
for i in range(1,nlines+1):
listFile.append(fReverse.readline(),)
fReverse.close()
return listFile
此功能可以简化很多:
def tail(filename, number_lines):
with open(filename, 'r') as file:
with open('output.txt', 'w') as output:
reversed_lines = file.readlines()[::-1]
output.write('\n'.join([line.strip() for line in reversed_lines]))
return reversed_lines[:number_lines-1]
此功能可以简化很多:
def tail(filename, number_lines):
with open(filename, 'r') as file:
with open('output.txt', 'w') as output:
reversed_lines = file.readlines()[::-1]
output.write('\n'.join([line.strip() for line in reversed_lines]))
return reversed_lines[:number_lines-1]
Doh,这是有道理的。全部修复:)噢,这是有道理的。全部固定:)+1用于使用deque,因为它是这里应该使用的+1用于使用deque,因为它是这里应该使用的