5
\$\begingroup\$

I just started Python a few days ago, and I haven't programmed much before. I know my code is terrible; however, I would like someone to look it over. What I'm trying to do is create a photo "loop" that changes my Windows 7 login screen. I had a batch file doing it, but even though my code is crappy it does the job way better.

I'm using two separate scripts, and if possible I would like to combine them. Renamer.py only runs when new photos are added. It sets up the file names for LoginChanger.py. LoginChanger is picky in the filenames, but Renamer doesn't change the photos in a loop. So I have to use Renamer, then LoginChanger to loop the photos.

Renamer.py

#-------------------------------------------------------------------------------
# Name:        Renamer
# Purpose:     Renames all .jpg's in a dir from 0 - n (where "n" is the number of .jpg's.)
#              This is to be used in conjunction with loginchanger.py
# Author:      Nathan Snow
#
# Created:     13/01/2012
# Copyright:   (c) Nathan Snow 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import os

count = 0
count2 = 0
list1 = []
list2 = []

for filename2 in os.listdir('.'):
        if filename2.endswith('.jpg'):
            list1.append(filename2)
            while count < len(list1):
                os.rename(filename2, str(count)+"old.jpg")
                count += 1

for filename3 in os.listdir('.'):
        if filename3.endswith('.jpg'):
            list2.append(filename3)
            while count2 < len(list2):
                os.rename(filename3, str(count2)+".jpg")
                count2 += 1

LoginChanger.py

#-------------------------------------------------------------------------------
# Name:        LoginChanger
# Purpose:     This is to be used after renamer.py. This loops the properly named
#              .jpg's in a "circle" first to last, 2-1, 3-2, ..., and changes
#              0 to BackgroundDefault.jpg.
# Author:      Nathan Snow
#
# Created:     13/01/2012
# Copyright:   (c) Nathan Snow 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import os

count = 0
list1 = []
list2 = []
list3 = []

for filename in os.listdir('.'):
    if filename.endswith('.jpg'):
        list3.append(filename)
        list3len = len(list3)
        list3len = list3len - 1
    if filename.startswith('BackgroundDefault'):
        os.rename('BackgroundDefault.jpg', str(list3len)+'.jpg')

for filename2 in os.listdir('.'):
    if filename2.endswith('.jpg'):
        list1.append(filename2)
        while count < len(list1):
            jpg = str(count)+'.jpg'
            oldjpg = str(count)+'old.jpg'
            os.rename(str(jpg), str(oldjpg))
            count += 1

for filename4 in os.listdir('.'):
    if filename4.startswith('0'):
        os.rename('0old.jpg', 'BackgroundDefault.jpg')

count = 1
count2 = 0

for filename3 in os.listdir('.'):
    if filename3.endswith('.jpg'):
        list2.append(filename3)
        while count < len(list2):
            newjpg = str(count2)+'.jpg'
            oldjpg = str(count)+'old.jpg'
            os.rename(str(oldjpg), str(newjpg))
            count2 += 1
            count += 1

print ('Created new login background')
\$\endgroup\$
3
\$\begingroup\$

You could avoid continuously renaming all files by overwriting just BackgroundDefault.jpg file instead e.g., change-background.py:

#!/usr/bin/env python
import bisect
import codecs
import os
import shutil

BG_FILE = u'BackgroundDefault.jpg'
db_file = 'change-background.db'
db_encoding = 'utf-8'

# read image filenames; sort to use bisect later
files = sorted(f for f in os.listdir(u'.')
               if f.lower().endswith(('.jpg', '.jpeg')) and os.path.isfile(f)) 
try: files.remove(BG_FILE)
except ValueError: pass # the first run

# read filename to use as a background from db_file
try:
    # support Unicode names, use human-readable format
    with codecs.open(db_file, encoding=db_encoding) as f:
         bg_file = f.read().strip()
except IOError: # the first run
    bg_file = files[0] # at least one image file must be present

# change background image: copy bg_file to BG_FILE
tmp_file = BG_FILE+'.tmp'
shutil.copy2(bg_file, tmp_file)
# make (non-atomic) rename() work even if destination exists on Windows
try: os.remove(BG_FILE)
except OSError: # in use or doesn't exist yet (the first run)
    if os.path.exists(BG_FILE):
       os.remove(tmp_file)
       raise
os.rename(tmp_file, BG_FILE)

# write the next filename to use as a background
next_file = files[bisect.bisect(files, bg_file) % len(files)]
with codecs.open(db_file, 'w', encoding=db_encoding) as f:
     f.write(next_file)
\$\endgroup\$
  • \$\begingroup\$ I copied this and it worked the first time. Then it said it couldn't change the background image because the file was already there. I had to remove a ")" from "files = sorted(glob.glob(u'*.jpg')))" to get it to work as well. I really appreciate the help though, Thanks. \$\endgroup\$ – japtain.cack Jan 15 '12 at 3:08
  • \$\begingroup\$ @Jedimaster0: I've fixed the code. I don't use Windows so it is untested. \$\endgroup\$ – jfs Jan 15 '12 at 4:18
3
\$\begingroup\$
  • Your variable names are pretty bad: filename1, filename2, filename3, ... is bad, use something more meaningful.
  • There is no need to use different loop variables in consecutive loops. Use filename everytime.
  • You need to move the #!/usr/bin/env python shebang line to the first line of the file or it won't work at all.
  • You have unnecessary str() calls in os.rename(str(oldjpg), str(newjpg)) - both variables are already strings.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.