将相同的数据写入文本文件python中的多行

时间:2013-09-26 04:03:39

标签: python-2.7 text-files

我想将许多行的相同信息写入文本文件。基本上,我有一个数字列表。我想将这些数字写在一行中,然后将第一行复制到下一行400行。

目前我的代码是

outfile = open(outfilename+'.dat','w')
for j in range (0,len(elevation_list)):
    outfile.write(elevation_list[j]+' ')
outfile.close()

它只写第一行。

例如,我的提升列表是1,2,3,4,5 我希望我的文本文件如下

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

您的提升列表中是否有换行符?试试这个:

elevations = ""
for elevation in elevation_list:
    elevations+= elevation

outfile = open(outfilename+'.dat','w')
for i in range(400):
    outfile.write(elevations +'\n')

outfile.close()

答案 1 :(得分:0)

这就是你想要的:

class RepeatedWrite(object):

    def __init__(self, elevation_list, no_of_lines=5, outfilename="outfile.dat"):
        self.elevation_list = elevation_list
        self.no_of_lines = no_of_lines
        self.outfilename = outfilename

    def write_to_file(self):
        with open(self.outfilename, 'w') as fp:
            for i in xrange(self.no_of_lines):
                fp.write(' '.join([str(ele) for ele in self.elevation_list]))
                fp.write("\n")


elevation_list = [1, 2, 3, 4, 5]

RepeatedWrite(elevation_list).write_to_file()