如何解决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',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 不起作用(不返回任何元素),但手动方式与文件输入一样有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。