所以我正在閱讀這個PPM文件,逐行閱讀,在這裏和那裏操縱它,並寫出新行到另一個文件。我嘗試製作一個最小的工作示例來重現行爲,但是當我編寫一個最小的示例時,奇怪的行爲消失了 - 但我無法弄清楚這是什麼部分導致了奇怪的行爲。所以完整的代碼如下。奇怪的行爲從枚舉()
def flip_horizontal(infile, outfile):
with open(os.getcwd() + '\\' + infile, 'r') as f:
outfile = open(os.getcwd() + '\\' + outfile, 'w')
rgbCounter = 0
for i, line in enumerate(f):
if i < 3:
outfile.write(line)
if i == 1:
width = int(line.split()[1])
lineList = [None for i in range(width*3)]
if width > 1024:
print "Image size too large: Buffer can only store 1024 \
pixels at a time. Aborting negate_red."
break
if i > 2:
print line
for integer in line.split():
if rgbCounter%3 == 0:
lineList[width*3-rgbCounter-3] = integer
elif rgbCounter%3 == 1:
lineList[width*3-rgbCounter-1] = integer
else:
lineList[width*3-rgbCounter+1] = integer
rgbCounter += 1
if rgbCounter == width*3:
outfile.write(' '.join(lineList))
outfile.write('\n')
rgbCounter = 0
outfile.close()
而這裏的問題:當我運行這段代碼,if i > 2:
後的「打印」還行打印線2(或者更確切地說,第3行,行於2索引)!在一個更小例子,如果我只是說
...
if i > 2:
print line
...
它只會打印行4和以後的事,但關於我實際運行代碼的其餘部分使得打印線3.任何想法,爲什麼和如何解決這個問題?
這裏的一個樣本輸入:
P3
4 4
255
49 49 49 100 100 100 0 200 0 0 0 0
100 100 100 100 0 0 200 200 200 255 255 255
200 100 0 0 100 200 0 0 0 50 50 50
0 0 0 0 0 0 0 0 0 0 0 0
,當我運行代碼我得到的印刷線路
4 4
49 49 49 100 100 100 0 200 0 0 0 0
100 100 100 100 0 0 200 200 200 255 255 255
...
第一行,含「4 4」不應該在那裏。
「當我寫的小例子,行爲怪異消失」是寫在首位最小的例子的原因主要部分。這給你一個完美的方式來進行:加回你跳過的東西的一半。問題是否回來了?然後將其中一半退出。如果沒有,將其餘一半的東西放回去。等等。在大約2-3次迭代中,您通常可以確切地確定事情出錯的地方。 – abarnert 2014-10-17 00:29:13
同時,請提供一些樣本輸入,以及所需的和實際的輸出。 – abarnert 2014-10-17 00:30:44
作爲一個附註,你顯然知道'with'語句,因爲你使用'infile'。那麼爲什麼你不使用'outfile'呢? (另外,你爲什麼重複使用'outfile'這個名字來表示文件名和打開的文件對象?這種事情在調試的時候會導致混亂。) – abarnert 2014-10-17 00:31:57