python:文件的迭代器类封装失败?

2024-09-30 14:19:16 发布

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

下面的python代码接受两个输入文件并对它们进行迭代 首先手动,然后使用fileiter类 但是对于管道,fileiter类失败,但是,该类的迭代器只是“open()”? 为什么会这样?python如何以等效的方式迭代文件和管道

t.py


#!/bin/python

import sys,os
from pathlib import Path
from collections.abc import Iterable
#print(os.fstat(fpath))
class FileIter:
  def __init__(self, filename):
    self.filename = filename

  def __iter__(self):
    return open(self.filename, 'rb')
def check(fpath):
    print(os.access(fpath,os.F_OK))
    print(os.access(fpath,os.R_OK))
    print(os.path.isfile(fpath))
    a=open(fpath,'rb')
    print('type',type(a),isinstance(a, Iterable))
    print('peek',a.peek())
    ai=iter(a)
    try:
        print('next',next(ai) )
    except:
        print('nonext')
        
    for i in a:
        print('for',type(i),i)
    a.close()
    print('####')
    print('FileIter')
    f=FileIter(fpath)
    ai=iter(f)
    try:
        print('next',next(ai) )
    except:
        print('nonext')
        
    for i in f:
        print('for',type(i),i)
for i in range(1,3):
    print(i)
    check(sys.argv[i])
    print(f'{i} end\n')

现在创建一个测试文件,并用它和一个管道调用python代码

for i in {1..3}; do echo test$i; done > /tmp/a

./t.py a <(cat a)
1
True
True
True
type <class '_io.BufferedReader'> True
peek b'test1\ntest2\ntest3\n'
next b'test1\n'
for <class 'bytes'> b'test2\n'
for <class 'bytes'> b'test3\n'
####
FileIter
next b'test1\n'
for <class 'bytes'> b'test1\n'
for <class 'bytes'> b'test2\n'
for <class 'bytes'> b'test3\n'
1 end

2
True
True
False
type <class '_io.BufferedReader'> True
peek b'test1\ntest2\ntest3\n'
next b'test1\n'
for <class 'bytes'> b'test2\n'
for <class 'bytes'> b'test3\n'
####
FileIter
nonext
2 end

从管道中可以看出,fileiter不工作(不返回任何元素),但手动方式与文件输入一样工作


Tags: 文件selftrueforbytes管道ostype