2012-11-04 124 views
2

我的代碼是:蟒蛇3無法寫入文件

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') 

我想打印在一個文本文件中的結果,但我得到這個錯誤:

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

回答

9

file應該是一個文件對象,而不是文件名。文件對象有write方法,str對象沒有。

從文檔上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.

還要注意的是,文件應該是開放的寫作:

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

查看更多關於open功能here