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)