检测每个输入文件的最后一行(检查EOF)

时间:2013-08-14 11:14:48

标签: python

我想处理一些文本文件并检测每个文本文件的最后一行,以便在那时进行一些操作。在这个简化的例子中,打印文件名,总行数和奇数。假设以下文件内容:

==> file1 <==
one
two
three

==> file2 <==
monday
tuesday
wednesday
thursday

==> file3 <==
red
green
blue

这就是我在perl中实现它的方法:

#!/usr/bin/env perl

use strict;
use warnings;

my (@odd);

while ( <> ) {
        print $_;
        if ( $. & 1 ) {
                chomp;
                push @odd, $_;
        }
        if ( eof ) {
                print $ARGV, ' -- ', $., "\n";
                print 'Odd lines => ', join( ':', @odd ), "\n";
                undef @odd;
                close ARGV;
        }
}

对于那些不习惯的人,<>fileinput.input()类似,ARGV是我明确关闭以重置行号计数器$.的文件句柄)。我希望这很容易理解。关键部分是检查eof

但这是我尝试使用python

的方法
#!/usr/bin/env python3

from fileinput import *

fname = ''
lnumber = 0
odd = []
try:
    for line in input():   
        if filelineno() == 1 and fname:
            print('{0} -- {1}'.format(fname, lnumber))
            print('Odd lines => {0}'.format(':'.join(odd)))
            odd = []
            fname = ''
            lnumber = 0
        lnumber += 1
        print('{0}'.format(line), end='')
        if lnumber & 1:
            odd.append(line.rstrip())
        if not fname:
            fname = filename()
        if not line:
            print('Is this end of line??')
except OSError as e:
    print('Operation failed: {0}'.format(e.strerror))
except EOFError as e:
    print('EOF found: {0}'.format(e.strerror))
except StopIteration:
    print('StopIteration reached')
finally:
    print('{0} -- {1}'.format(fname, lnumber))
    print('Odd lines => {0}'.format(':'.join(odd)))
    close()

像以下一样运行:

python3 script.py file[123]

两个脚本产生相同的结果:

one
two
three
file1 -- 3
Odd lines => one:three
monday
tuesday
wednesday
thursday
file2 -- 4
Odd lines => monday:wednesday
red
green
blue
file3 -- 3
Odd lines => red:blue

它做我想要的但不是我想要的方式。 StopIterationEOFError或空行检查都不会检测到最后一行。使用其他变量和fileinput.filelineno()来处理前一个文件对我来说似乎很奇怪,至少与perl相比。我错过了什么?你会如何以更好的方式解决这类问题?

1 个答案:

答案 0 :(得分:1)

类似的东西:

import fileinput
from itertools import islice

for filename in list_of_filenames:
    fin = fileinput.input(filename)
    odd = [line.strip() for line in islice(fin, None, None, 2)]
    # We'll be at EOF at this point...
    print(fin.lineno(), odd)