制作尾部功能:反转文件中的行

时间:2014-03-11 18:58:10

标签: python python-2.7

我试图定义一个输出文件中最后n行的函数。下面的函数似乎主要起作用,除了fReverse的前两行正在加入的事实,我无法弄清楚为什么......

示例:(我尝试将这些放在blockquotes而不是代码中,但它会破坏行格式化)

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.  

fReverse =

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)))

4 个答案:

答案 0 :(得分:4)

在这里更容易使用deque

要反转整个文件:

from collections import deque

with open('file') as fin:
    reversed_lines = deque()
    reversed_lines.extendleft(fin)

要显示最后一个n(但首先遍历所有行):

with open('file') as fin:
    last4 = deque(fin, 4)

答案 1 :(得分: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]

答案 2 :(得分:0)

那是因为最后一行在结尾处没有\n; P

您可以尝试:

lines = reversed([l.strip()+'\n' for l in f])
fReverse.writelines(lines)

答案 3 :(得分:0)

这里的问题是文件的最后一行不以换行符结尾。因此,f.readlines()将类似于以下内容(请注意,最终条目没有\n):

['Darkly I gaze into the days ahead,\n',
 'And see her might and granite wonders there,\n',
 'Beneath the touch of Time’s unerring hand,\n',
 'Like priceless treasures sinking in the sand.']

所以当你反过来时,你最终会把你的第一个"行"写到文件中。实际上并没有写\nfReverse.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