使用Python在每一行之后插入换行符

时间:2015-07-14 13:02:09

标签: python formatting

我尝试在每行之后将换行符插入文本文件中。

所以如果这是我的数据:

Dose    atRA_minus_tet  tet

0.001   5.100033162 0

0.001967886 9.651369961 0

0.003926449 16.72520921 0

我想:

def prepare_steady_state_data(self,data_file):
    with open(data_file) as f:
        lines= [line+'\n' for line in f.readlines()]

    with open(data_file[:-4]+'_for_SS_Fit.txt','w') as f:
        f.write(str(lines))

我的代码:

['Dose,Cyp26(atRA_plus_tet),Tet\n\n', '0.001,26.67599946,1\n\n', '0.001006932,26.89620879,1\n\n', '0.001013911,27.117882,1\n\n', '0.001020939,27.34102614,1\n\n']

问题是这会按字面意思写出字符串,如下所示:

String

如何更改此代码以便在输出文本文件中获得所需的格式?

谢谢,

Ciaran

2 个答案:

答案 0 :(得分:4)

with open(data_file) as source:
    with open(data_file[:-4]+'_for_SS_Fit.txt','w') as output:
        for line in source:
            f.write(line+'\n')

答案 1 :(得分:1)

替换此行

f.write(str(lines))

使用

f.write(''.join(lines))