Pregunta

Im writing a program that changes my desktop background. It does this by reading a text file. If the text file says one of the BG file names it saves that one as my background, and writes the name of the other one to the file and closes it.

I can't seem to get it to work.
Here is my code:

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)

When I use "r+" it gives me this error:

Traceback (most recent call last):
  File "C:\BG\BG Switch.py", line 13, in <module>
    BGfile.write('mod_bg.bmp')
IOError: [Errno 0] Error

Which isn't helpful at all!
When I use "w+" it just erases what's already in the file.

Can anyone tell me why I'm getting this weird error, and a possible way to fix it?

¿Fue útil?

Solución

Just re-open the file in write mode after reading:

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)

If you are opening the file to both read and write, you must at least rewind to the start of the file and truncate before writing:

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)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top