将函数结果附加到文件

时间:2016-01-18 20:42:21

标签: python list ascii

我正在尝试运行一个函数,该函数在一个数字范围内返回两个值,并将返回的值存储到ASCII.txt文件中。

我的代码是:

site = np.genfromtxt('...\Plot_1.txt', dtype=None, delimiter='\t')

def process(matrix, kernel_size, kernel_dilation, kernel_zs, kernel_norm, local_chm, threshold_value):
    ker_size = kernel_size
    ker_bx = 0
    ker_by = 0
    ker_a = kernel_dilation
    ker_zs = kernel_zs
    ker_norm = kernel_norm
    loc_chm = local_chm
    th_value = threshold_value        

    return ker_size, nr_trees #both are float numbers

for i in range(1, 6, 2):
    list = []
    a = process(site, 5, i, 2, 1, 2, 0.9) #This is the function, only returns two values
    print a, type(a), np.shape(a)
    list.append(a)
    print list
    with open('E:\Test_matrix_automatic.txt', 'a') as outfile:
        outfile.write(list)

它给出错误:

  

TypeError:期望字符串或其他字符缓冲区对象

我不知道如何解决这个问题。我没有使用返回两个值的函数。

1 个答案:

答案 0 :(得分:2)

您从process()返回一个浮点元组并将其追加到列表中。 正如错误消息所述,文件对象的write() - 方法需要一个字符串或一个字符缓冲区对象,但是你要将它包含一个包含浮点元组的列表。 您应该在打印之前将列表转换为字符串。

您可以尝试这样的事情:

with open('E:\Test_matrix_automatic.txt', 'a') as outfile:
    for item in list:
        outfile.write(str(item) + '\n')
相关问题