Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

Here is my code, however it limits the number of photos I can have to 9. If I have 10 or more photos, it starts failing and renaming things wrong.

LoginChanger.py

#!/usr/bin/env python
import os

list1 = []
count1 = 0

# Finds jpg files and makes list.
for filename in os.listdir('.'):
    if filename.endswith(('.jpg', '.JPG', 'jpeg', '.JPEG', '.Jpg', '.Jpeg')):
        list1.append(filename)
        list1end = len(list1)

    # Finds background file and sends it to the back of the list.
    if filename.startswith(('BackgroundDefault', 'backgrounddefault')):

        # If name already exists for some reason, makes old file.
        if str(list1end - 1)+'.jpg' in list1:
            os.rename('BackgroundDefault.jpg', 'OldBackground.jpg')
        else:
            os.rename('BackgroundDefault.jpg', str(list1end - 1)+'.jpg')
# Resets The list.
list1 = []

# Creates a list with all jpgs.
for filename in os.listdir('.'):
    if filename.endswith(('.jpg', '.JPG', 'jpeg', '.JPEG', '.Jpg', '.Jpeg')):
        list1.append(filename)
        list1end = len(list1)

# Renames the beginning object of list to background file.
os.rename(list1[0], 'BackgroundDefault.jpg')

# Renames all files incrementally.
while count1 < list1end - 1:
    oldname = list1[count1 + 1]
    os.rename(oldname, str(count1)+'.jpg')
    count1 += 1

print ('Login Background Has Been Changed.')
share|improve this question

2 Answers

up vote 2 down vote accepted

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)
share|improve this answer
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. – Jedimaster0 Jan 15 '12 at 3:08
@Jedimaster0: I've fixed the code. I don't use Windows so it is untested. – J.F. Sebastian Jan 15 '12 at 4:18
It works great! thanks. I will try to make my own like this. This gives me a great starting point. – Jedimaster0 Jan 15 '12 at 5:50
  • 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.
share|improve this answer
Thanks I will try to apply this. – Jedimaster0 Jan 15 '12 at 3:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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