2014-10-16 155 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')