Python:将float数组写入文件

时间:2015-11-17 19:48:39

标签: python arrays python-2.7

将float数组写入文件的最简洁,最简单的方法是什么? 这就是我想要做的。 mylist是数组。

awk -F'|' -v OFS='|' '
    NR == 1 {header = $1 OFS $2 OFS $3; next}
    { 
        f = "Company_" $4 ".txt"; 
        if (!seen[f]) {
            print header > f
            seen[f] = 1
        }
        print $1,$2,$3 > f 
    }
' input.txt

我的列表如下:

match = re.search(r"DeltaE =\s+(\S+).* Intensity =\s+(\S+)", line)
    if match is not None:
        self.deltae = float(match.group(1))
        self.intensity = float(match.group(2))
        mylist = [self.deltae, self.intensity]
        with open("Test.txt", 'w') as myfile:
             for range(sublist) in mylist:
                myfile.write(', '.join(str(item) for item in sublist)+'\n')
        print(mylist)

enter image description here

1 个答案:

答案 0 :(得分:0)

假设mylist是一个2元素列表,您可以使用生成器表达式:

with open("Test.txt", 'a') as myfile:
    myfile.write(', '.join(str(item) for item in mylist)+'\n')

或过时mapfloat映射到str

with open("Test.txt", 'a') as myfile:
    myfile.write(', '.join(map(str, mylist))+'\n')

如果在循环内定义mylist,则需要在同一循环内运行此代码以处理所有行。