0

我想将多行的相同信息写入文本文件。基本上,我有一个数字列表。我想将这些数字写在一行中,然后将第一行复制到接下来的 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

谁能帮我解决这个问题?

4

2 回答 2

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()
于 2013-09-26T16:53:58.167 回答
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()
于 2013-09-26T04:05:28.657 回答