Search code examples
pythonfilereadfilewritefilepbm

How to make space between every two pixels in a pbm file(ASCII mode)


I have a test.pbm file in ASCII mode containing the code as follows:

P1
# Comment
9 9
000000000
011000000
011000000
011000000
011000000
011000010
011111110
011111110
000000000   

I want to make a new file "newFile.pbm" which will contain space between every two pixels. Like as follows:

P1
# Comment
9 9
0 0 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0
0 1 1 0 0 0 0 1 0
0 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 0
0 0 0 0 0 0 0 0 0 

I have tried to open the file "test.pbm" with the following code to do the work, but I have faced many problems, firstly, it shows 'IOError: cannot identify image file' when opening .pbm, secondly, can not make the space between every two pixels. Actually I am new in Python. My os Linux Mint 17.3 cinamon 32bit and Python2.7.6. Plese help. The code I have tried given below:

fo=open("test.pbm",'r')  
columnSize, rowSize=fo.size
x=fo.readlines()
fn = open("newfile.pbm","w") 
for i in range(columnSize):
     for j in range(rowSize):
      fn.write(x[i][j])
fn.close()

Solution

  • You could do something like this:

    with open("test.pbm", 'r') as f:
        image = f.readlines()
    
    with open("newfile.pbm", "w") as f:
        f.writelines(image[:3])   # rewrite the header with no change
        for line in image[3:]:    # expand the remaining lines
            f.write(' '.join(line))