写入文件时出现IOError

3
我正在编写一个程序,用于更改我的桌面背景。它通过读取文本文件来实现。如果文本文件中写入了某个背景文件名,则将其保存为我的桌面背景,并将另一个文件名写入该文件并关闭它。
我无法让它正常工作。 以下是我的代码:
import sys, os, ctypes

BGfile = open('C:\BG\BG.txt', 'r+' )
BGread = BGfile.read()
x=0
if BGread == 'mod_bg.bmp':
    x = 'BGMATRIX.bmp'
    BGfile.write('BGMATRIX.bmp')
    BGfile.close()

elif BGread == 'BGMATRIX.bmp':
    x = 'mod_bg.bmp'
    BGfile.write('mod_bg.bmp')
    BGfile.close()

pathToImg = x
SPI_SETDESKWALLPAPER = 20  
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, pathToImg, 0)

当我使用"r+"时,会出现以下错误:
Traceback (most recent call last):
  File "C:\BG\BG Switch.py", line 13, in <module>
    BGfile.write('mod_bg.bmp')
IOError: [Errno 0] Error

这一点都不有用!


当我使用"w+"时,它只会擦除文件中已经存在的内容。

有人可以告诉我为什么会出现这个奇怪的错误,并提供可能的解决方法吗?


是的,我只是用名字来记住哪个是哪个,这就是为什么我得到了-1吗? - Serial
我前几天做了类似这样的东西。 - Noelkd
1个回答

4

在读取后以写模式重新打开文件:

with open('C:\BG\BG.txt') as bgfile:
    background = bgfile.read()

background = 'BGMATRIX.bmp' if background == 'mod_bg.bmp' else 'mod_bg.bmp'

with open('C:\BG\BG.txt', 'w') as bgfile:
    bgfile.write(background)

SPI_SETDESKWALLPAPER = 20  
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, background, 0)

如果您要打开文件进行读写,您必须至少在写入之前将其倒回到文件的开头并截断文件:
with open('C:\BG\BG.txt', 'r+') as bgfile:
    background = bgfile.read()

    background = 'BGMATRIX.bmp' if background == 'mod_bg.bmp' else 'mod_bg.bmp'

    bgfile.seek(0)
    bgfile.truncate() 
    bgfile.write(background)

SPI_SETDESKWALLPAPER = 20  
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, background, 0)

哦,那很有道理。我做了你解释的事情,只是有点不同。谢谢! - Serial

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接