È possibile imitare l'idioma C in Python.
Per leggere un buffer fino a max_size
numero di byte, si può fare questo:
with open(filename,'rb') as f:
while True:
buf=f.read(max_size)
if not buf: break
process(buf)
Oppure, una linea di file di testo per riga:
# warning -- not idiomatic Python! See below...
with open(filename,'rb') as f:
while True:
line=f.readline()
if not line: break
process(line)
È necessario utilizzare while True/break
costrutto dal c'è lo no eof test in Python oltre alla mancanza di byte restituiti da una lettura.
In C, si potrebbe avere:
while ((ch != '\n') && (ch != EOF)){
// read the next ch and add to a buffer
// ..
}
Tuttavia, non si può avere questo in Python:
while(line=f.readline()):
# syntax error
perché assignments are not allowed in expressions in Python.
è certamente più idiomatica in Python per fare questo:
# THIS IS IDIOMATIC Python. Do this:
with open('somefile') as f:
for line in f:
process(line)
Grazie, BTW, come posso fare questo per raw_input(), ovvero l'input std. –
devi usare 'sys.stdin' per farlo – jozefg
Grazie, la parte" sys.stdin "mi aiuta davvero. –