21.12.2022 Views

python_para_desenvolvedores_2ed

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Exceções 89

import random

# Cria um arquivo com 25 números randômicos

with file('temp.txt', 'w') as temp:

for y in range(5):

for x in range(5):

# "print >> " grava a saída do comando no arquivo indicado

print >> temp, '%.2f' % random.random(),

print >> temp

# Exibe o conteúdo do arquivo

with file('temp.txt') as temp:

for i in temp:

print i,

# Fora dos blocos, o arquivo está fechado

# Isso gera uma exceção ValueError: I/O operation on closed file

print >> temp

Exemplo de saída:

0.61 0.09 0.91 0.94 0.11

0.41 0.01 0.88 0.61 0.91

0.49 0.54 0.29 0.72 0.42

0.44 0.75 0.47 0.62 0.73

0.13 0.66 0.87 0.60 0.35

Traceback (most recent call last):

File "wt01.py", line 15, in <module>

print >> temp

ValueError: I/O operation on closed file

Como o arquivo foi fechado ao final do bloco, a tentativa de gravação gera

uma exceção.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!