[Python] Leggere n righe da un file.

Carlos Catucci carlos.catucci a gmail.com
Dom 12 Maggio 2013 22:46:25 CEST


ecco come viene descritta:

> readlines([hint])
> Read and return a list of lines from the stream. hint can be specified
> to control the number of lines read: no more lines will be read if the
> total size (in bytes/characters) of all lines so far exceeds hint.
>
> forse sto interpretando male io quel parametro "hint", pensavo che
> imponendo file.readlines(6) leggessi solo le prime 6 righe del file
> (se non faccio altre iterazioni)...
>
> ed invece mi ritrovo che legge TUTTE le righe del file... cosa sto
> sbagliando nell'interpretazione del manuale?


Allora un semplice help su readlines

readlines(...)
    readlines([size]) -> list of strings, each a line from the file.

    Call readline() repeatedly and return a list of the lines so read.
    The optional size argument, if given, is an approximate bound on the
    total number of bytes in the lines returned.

Chiaramente puoi sempre usare lo slicing per leggere solo le prime n righe

ifile = open("miofile,txt","r")
rows = ifile.readlines()
print rows[:6]

Pero' se il file fosse troppo lungo potresti avere problemi di memoria (mi
e' capitato di recente con degli huge xml files). Il ciclo while con la
readline puo' aiutare ad evitare.

Carlos
-- 
..y sobre todo, sean siempre capaces de sentir en lo más hondo cualquier
injusticia cometida contra cualquiera en cualquier parte del mundo. Es la
cualidad más linda de un revolucionario." -  Ernesto Guevara de la Serna
Lynch
-------------- parte successiva --------------
Un allegato HTML č stato rimosso...
URL: <http://lists.python.it/pipermail/python/attachments/20130512/78991e72/attachment-0001.html>


Maggiori informazioni sulla lista Python