python 3无法写入文件

kha*_*eeb 2 python file attributeerror python-3.x

我的代码是:

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')
Run Code Online (Sandbox Code Playgroud)

我想在文本文件中打印结果,但是我收到此错误:

dtint, llen, dlen), file='redata.txt')
AttributeError: 'str' object has no attribute 'write'
Run Code Online (Sandbox Code Playgroud)

Lev*_*sky 9

file应该是文件对象,而不是文件名.文件对象有write方法,str对象没有.

来自以下文件print:

文件参数必须是与对象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)
Run Code Online (Sandbox Code Playgroud)

查看更多有关的open功能在这里.