我试图定义一个函数,输出文件中的最后n行。下面的函数似乎大部分都起作用了,除了fReverse中的前两行正在连接,我不明白为什么。。。你知道吗
示例:(我尝试将这些代码放在块引号中而不是代码中,但这会破坏行格式)
f=
Darkly I gaze into the days ahead,
And see her might and granite wonders there,
Beneath the touch of Time’s unerring hand,
Like priceless treasures sinking in the sand.
弗雷弗斯=
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,
代码:
def tail(filename, nlines):
'''Returns a list containing the last n lines of the file.'''
f = open(filename, 'r')
fReverse = open('output.txt', 'w')
fReverse.writelines(reversed(f.readlines()))
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
fname = raw_input('What is the name of the file? ')
lines = int(raw_input('Number of lines to display? '))
print "The last %d lines of the file are: \n%s" % (lines, ''.join(tail(fname, lines)))
这个函数可以简化很多:
在这里使用
deque
更容易:要反转整个文件:
要显示最后的
n
(但首先遍历所有行):这里的问题是文件的最后一行没有以换行符结束。因此
f.readlines()
将类似于以下内容(注意,最终条目没有\n
):因此,当您反转此操作时,您的第一个“行”实际上不会写入
\n
,并且fReverse.writelines()
不会添加自动结束的行。要解决此问题,只需检查f.readlines()
的最后一行是否以\n
结尾,并在必要时添加它:相关问题 更多 >
编程相关推荐