gpt4 book ai didi

python - 未知的 Python 错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:01:08 24 4
gpt4 key购买 nike

以下代码来 self 正在编写的 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')

最佳答案

您重新分配给 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() 时会遇到错误,但变量名称可能不是您发布的问题的原因。

关于python - 未知的 Python 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5226502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com