2011-03-07 63 views
1

以下代碼來自我正在編寫的python腳本,它應該修改Arch Linux rc.conf文件中的守護程序數組。然而,當運行時,我得到一個ValueError說操作:未知的Python錯誤

for line in rc: 

不能在一個關閉的文件上執行。我可能會錯過一些東西,但據我所知,該文件並未關閉。謝謝。

rc = open('/etc/rc.conf', 'r') 
tmp = open('/etc/rctmp', 'w') 
for line in rc: 
    if 'DAEMONS' in line and '#' not in line and 'dbus' not in line: 
     line = line.split('=')[1].strip() 
     line = line[1:len(line)-1] 
     line = line.split() 
     tmp = line[1:] 
     line = [line[0]] 
     line = ' '.join(line + ['dbus'] + tmp) 
     line = 'DAEMONS = (' + line + ')' 
tmp.write(line) 
rc.close() 
tmp.close() 
#os.remove('/etc/rc.conf') 
#shutil.move('/etc/rctmp', '/etc/rc.conf') 
+1

'tmp.write(line)'的縮進是錯誤的,其餘的確很奇怪。無論如何,粘貼代碼和回溯照原樣。 – 2011-03-07 23:50:24

回答

4

您重新分配給tmp約8臺詞背下來了。然後,tmp不再是該文件。那時,它的引用計數可能會降到零,所以Python會關閉它。儘管你仍然試圖循環播放其他文件中的行。

使用不同的變量名的位置:

... 
tmp = line[1:]  # rename 'tmp' here 
line = [line[0]] 
line = ' '.join(line + ['dbus'] + tmp) # and also here 
... 

[編輯...]

我只注意到你是從RC讀,還沒有寫,當你錯誤TMP的。儘管在嘗試tmp.write()時會出現錯誤,但變量名可能不是您發佈的問題的原因。

0

我有一個輕微的預感,你的縮進是關閉的。嘗試用這個代替你的代碼塊。

from contextlib import nested 

with nested(open('/etc/rc.conf', 'r'), open('/etc/rctmp', 'w')) as managers: 
    rc_file, tmp_file = managers 
    for line in rc_file: 
     if 'DAEMONS' in line and '#' not in line and 'dbus' not in line: 
      line = line.split('=')[1].strip() 
      line = line[1:len(line) - 1] 
      line = line.split() 
      tmp = line[1:] 
      line = [line[0]] 
      line = ' '.join(line + ['dbus'] + tmp) 
      line = 'DAEMONS = (' + line + ')' 
     tmp_file.write(line) 

編輯:@ dappawit的答案也是正確的,當行結束滿足if條件爲,你的代碼將一個字符串綁定到它掩蓋了tmp變量,然後,另一個錯誤的線沿線退出條件塊後將拋出string object doesn't have a write method