Python - 将 For Loop 编写为文件作为生成器而不是 str/dict

标签 python

我是一名初级开发人员,我正在尝试将 for 循环中的以下变量写入文件,但当它是生成器时,它正试图写入 str。在尝试使用第二种方法时,我还收到了不受支持的操作数类型。

divdir = conn.extend.standard.paged_search('cn = All.DL Div DSS Directors, ou = Distribution Lists, ou = Exchange, dc=google,dc=corpad,dc=net', '(objectClass=*)', attributes=['member'])
for b in divdir:
    with open ('test2.txt', 'w') as file:
        file.write (b)

我还尝试了以下方法:

divdir = conn.extend.standard.paged_search('cn = All.DL Div DSS Directors, ou = Distribution Lists, ou = Exchange, dc=google,dc=corpad,dc=net', '(objectClass=*)', attributes=['member'])
my_file=open("test2.txt","w")
for b in divdir:
    my_file.write(b.get('divdir')+'\n')
my_file.close()

它给出的错误是:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

最佳答案

综合考虑我的意见,您应该对以下调整后的陈述感到满意。

这会对预先准备好所有输出(包括设置 generator=False)的文件执行一次写入,并通过连接所有值一次写入:

divdir = conn.extend.standard.paged_search('cn = All.DL Div DSS Directors, ou = Distribution Lists, ou = Exchange, dc=google,dc=corpad,dc=net', '(objectClass=*)', attributes=['member'], generator=False)
directors = map(str, divdir)         #Stringify each director from generator
directors_str = '\n'.join(directors) #Join the list of directors with a newline
with open('test2.txt', 'w') as file:
    file.write(directors_str)        #Write to file

关于Python - 将 For Loop 编写为文件作为生成器而不是 str/dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51158992/

相关文章:

python - 在 Pandas groupby 上应用 ewm 函数

python - 如何从 pandas date_range 中删除日期

python - 使用 python 2.7 时内存泄漏

python - 在Python中访问列表列表的每个列表的内容

python - 使用txt文件中的数据回答python中的问题

python - 尝试加载多个json文件并合并为一个 Pandas 数据框

python - 如何在python中指定每行中的字符数?

python - 如何使用 python Ray 并行处理一个大列表?

python - 基于多列的运行计数

使用 Big Huge Thesaurus API 时出现 Python 错误