2

私のコードは次のとおりです。

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::%s@%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'
4

1 に答える 1

9

fileファイル名ではなく、ファイル オブジェクトである必要があります。ファイル オブジェクトにはwriteメソッドがありますが、strオブジェクトにはありません。

ドキュメントからprint

file引数は、write(string)メソッドを持つオブジェクトでなければなりません。存在しない場合None、またはsys.stdoutが使用されます。

また、ファイルは書き込み用に開いている必要があることに注意してください。

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関数の詳細については、こちらを参照してください。

于 2012-11-04T07:37:11.200 に答える