【问题标题】:python 3 unable to write to filepython 3无法写入文件
【发布时间】:2012-11-04 07:34:03
【问题描述】:

我的代码是:

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'

【问题讨论】:

    标签: python file python-3.x attributeerror


    【解决方案1】:

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

    来自print上的文档:

    file 参数必须是具有write(string) 方法的对象;如果它 不存在,否则将使用Nonesys.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 函数here

    【讨论】:

      猜你喜欢
      • 2014-09-03
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多