python 3无法写入fi

2024-06-09 06:50:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码是:

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

我想将结果打印到文本文件中,但出现以下错误:

^{pr2}$

Tags: infromimportforrangelcchoicerandrange
1条回答
网友
1楼 · 发布于 2024-06-09 06:50:32

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

来自^{}的文档:

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的更多信息。在

相关问题 更多 >