使尾部功能:在fi中反转线条

2024-09-30 14:18:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图定义一个函数,输出文件中的最后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)))

Tags: ofthe函数代码incloseopendays
3条回答

这个函数可以简化很多:

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]

在这里使用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)

这里的问题是文件的最后一行没有以换行符结束。因此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.']

因此,当您反转此操作时,您的第一个“行”实际上不会写入\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

相关问题 更多 >