以下代码来自我正在编写的python脚本,它应该修改Arch Linux rc.conf文件中的守护进程数组。但是在运行时,我得到一个ValueError,表示操作:
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')
答案 0 :(得分: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()
时会出现错误,但变量名称可能不是您发布的问题的原因。
答案 1 :(得分: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
行抛出。