2012-11-04 2 views
2

Mon code est:python 3 incapable d'écrire à déposer

from random import randrange, choice 
from string import ascii_lowercase as lc 
from sys import maxsize 
from time import ctime 

tlds = ('com', 'edu', 'net', 'org', 'gov') 

for i in range(randrange(5, 11)): 
    dtint = randrange(maxsize)      
    dtstr = ctime()         
    llen = randrange(4, 8)        
    login = ''.join(choice(lc)for j in range(llen)) 
    dlen = randrange(llen, 13)       
    dom = ''.join(choice(lc) for j in range(dlen)) 
    print('%s::%[email protected]%s.%s::%d-%d-%d' % (dtstr, login,dom, choice(tlds), 
            dtint, llen, dlen), file='redata.txt') 

Je veux imprimer les résultats dans un fichier texte, mais je reçois cette erreur:

dtint, llen, dlen), file='redata.txt') 
AttributeError: 'str' object has no attribute 'write' 

Répondre

9

file doit être un objet de fichier , pas un nom de fichier. Les objets de fichier ont la méthode write, les objets str non.

De la doc sur print:

The file argument must be an object with a write(string) method; if it is not present or None , sys.stdout will be used.

Notez également que le fichier doit être ouvert pour l'écriture:

with open('redata.txt', 'w') as redata: # note that it will overwrite old content 
    for i in range(randrange(5,11)): 
     ... 
     print('...', file=redata) 

En savoir plus sur la fonction openhere.

Questions connexes