2014-10-16 154 views
-4

我有一个字符串,我从文件中读取的名单,我目前他们都转换成整数,然后从列表中去掉它们,我这样做如下图所示正确格式化数据

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 

我如何快速把我升ong字符串转换为出现在新行中的整数,而不是全部整合在一起?

感谢

这里是我写的文件

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

你可以显示代码写入文件的位置吗? – Anzel 2014-10-16 12:13:57

+1

你为什么要在列表上调用'str()',然后剥去'[]'?只需写一个循环。 – geoffspear 2014-10-16 12:14:41

+0

将代码torwite添加到上面的文件中 – user2065929 2014-10-16 12:17:40

回答

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')