如何将函数的输出写入文件?

时间:2017-09-09 18:37:45

标签: python-2.7

f = open('some_file.txt','a') chars =“ACGT”

def neighbors2(pattern,d):

sum ([neighbors(pattern, d2) for d2 in range(d + 1)], [])


for i in range(0,len(sum)):
    f.write(sum[i])
f.close()
assert(d <= len(pattern))

if d == 0:
    return [pattern]

r2 = neighbors(pattern[1:], d-1)
r = [c + r3 for r3 in r2 for c in chars if c != pattern[0]]

if (d < len(pattern)):
    r2 = neighbors(pattern[1:], d)
    r += [pattern[0] + r3 for r3 in r2]

return r

我正在尝试编写此函数的输出(这是ex:ACG的字符串),不包括模式''。但我尝试的代码会产生错误。 产生错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test14.py", line 9, in neighbors2
    for i in range(0,len(sum)):
TypeError: 'builtin_function_or_method' object is not iterable

更新 我设法将函数输出写入文件。但我需要知道如何从列表中删除''标记:(

1 个答案:

答案 0 :(得分:0)

使用with,例如

with open('some_file.txt', 'a') as f:
    for i in range(len(pattern)):
        f.write('%d\n' % i)

确保文件在退出块时正确close()

另外,在条件句中省略parens。使用if d < 2:,而不是if (d < 2):

并且肯定会在断言周围省略parens。将其短语为assert d <= len(pattern)