gpt4 book ai didi

python - 写入文件时出现 IOError

转载 作者:可可西里 更新时间:2023-11-01 09:20:50 26 4
gpt4 key购买 nike

我正在编写一个程序来更改我的桌面背景。它通过读取文本文件来完成此操作。如果文本文件显示其中一个 BG 文件名,它会将那个保存为我的背景,并将另一个的名称写入文件并关闭它。

我似乎无法让它工作。
这是我的代码:

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+" 时,它只会删除文件中已有的内容。

谁能告诉我为什么会出现这个奇怪的错误,以及可能的修复方法?

最佳答案

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

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)

关于python - 写入文件时出现 IOError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16802854/

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