正确格式化数据

时间:2014-10-16 12:11:59

标签: python

我有一个从文件中读取的字符串列表,我目前将它们全部转换为整数然后从列表中删除它们,我这样做如下所示

def reading_ppm(file_name):

    f = open (file_name)
    setting = f.readline().splitlines()
    comment = f.readline().splitlines()
    size_x, size_y = f.readline().split()
    pixel_max = f.readline().splitlines()
    orig_data = f.read().split()        

    return size_x,size_y,pixel_max, orig_data

data = map(int, orig_data)
data =  str(data).strip('[]')

当我将数据写入新文件时,我得到:

255, 255, 255, 255, 255, 255, 255, 255, 255,
然而,我想得到的是

255
255
255
255
255
255
255
255
255
255
255
255
255
255

如何快速将我的长字符串转换为出现在新行而不是一行中的整数?

由于

这是我写文件

def writting_ppm(ppm_file,size_x,size_y,maxval,data):
    colour = 'P3'
    print size_x
    print size_y
    # maxval =  str(maxval).strip('['']')
    maxval = 255
    # data =  str(data).strip('[]')
    # print data
    with open(ppm_file, "w") as text_file:
        text_file.write(colour + "\n" + "\n" +str(size_x) + " " + str(size_y) + "\n" + str(maxval) +"\n" + (data) )    

我正在尝试实现一个循环来执行此操作:

with open(ppm_file, "w") as text_file:
    text_file.write(colour + "\n" + "\n" +str(size_x) + " " + str(size_y) + "\n" + str(maxval) +"\n")
    count = 0
    while count < len(data):
        text_file.write(data[count] + "\n")
        count = count + 1

但我目前遇到错误,这是正确的方法吗?

1 个答案:

答案 0 :(得分:0)

你应该使用for循环,不要破解[]。像这样的东西:

def writting_ppm(ppm_file,size_x,size_y,maxval,data):
    colour = 'P3'
    print size_x
    print size_y
    # leave data as a list
    maxval =  max(maxval) # use max to get the max int in a list
    with open(ppm_file, "w") as text_file:
        text_file.write(colour + "\n" + "\n" +str(size_x) + " " + str(size_y) + "\n" + str(maxval) +"\n")
        for each in data:
            text_file.write(str(each)+'\n')