0

次のコードを含む ASCII モードのtest.pbmファイルがあります。

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

2 ピクセルごとにスペースを含む新しいファイル「newFile.pbm」を作成したいと考えています。次のように:

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 

作業を行うために次のコードでファイル「test.pbm」を開こうとしましたが、多くの問題に直面しました.1つ目は、.pbmを開くときに「IOError:画像ファイルを識別できません」と表示され、2つ目は作成できません2 ピクセルごとのスペース。実際、私はPythonが初めてです。私のOS Linux Mint 17.3 cinamon 32bit と Python2.7.6. 助けてください。私が試したコードは以下のとおりです。

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()
4

1 に答える 1

0

次のようなことができます。

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))
于 2016-11-30T17:27:27.717 に答える