微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

写入文件时出现IOError

我正在编写一个程序来更改我的桌面背景.它通过读取文本文件来实现.如果文本文件说其中一个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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐