Ciò che sostituisce xreadlines () in Python 3?
-
30-09-2019 - |
Domanda
In Python 2, oggetti file hanno avuto un xreadlines () metodo che ha restituito un iteratore che avrebbe letto quella linea di file alla volta. In Python 3, le xreadlines () metodo non esiste più, e realines () ancora restituisce una lista (non un iteratore). Fa Python 3 ha qualcosa di simile a xreadlines ()?
So che posso fare
for line in f:
anziché
for line in f.xreadlines():
Ma vorrei anche di utilizzare xreadlines () senza un ciclo for:
print(f.xreadlines()[7]) #read lines 0 to 7 and prints line 7
Soluzione
L'oggetto file stesso è già un iterabile.
>>> f = open('1.txt')
>>> f
<_io.TextIOWrapper name='1.txt' encoding='UTF-8'>
>>> next(f)
'1,B,-0.0522642316338,0.997268450092\n'
>>> next(f)
'2,B,-0.081127897359,2.05114559572\n'
Usa itertools.islice
per ottenere un elemento arbitrario da un iterabile.
>>> f.seek(0)
0
>>> next(islice(f, 7, None))
'8,A,-0.0518101108474,12.094341554\n'
Altri suggerimenti
come su questo (generatore di espressione):
>>> f = open("r2h_jvs")
>>> h = (x for x in f)
>>> type(h)
<type 'generator'>`
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow