Hey everybody,

I'd like to write a python script which renames a file on my desktop to a number which is 1 less than what it was before. If you're wondering, the number tells me how many days left 'till I finish high school, lol, but I've also got other things inside the file.

I'm still learning python (reading 'Learning Python') but I've been able to figure some of the commands I'll be using in this script.

import os
os.rename('C:/Users/Sam/Desktop/oldname.txt', 'C:/Users/Sam/Desktop/rename.txt')

But what I want to do is take the file I have on my desktop ('516.txt' as of today) and have a command that does something like 'filename -= 1'.

The problem is, I don't know how to attach the number in the filename to a variable. These commands might not exits (since I don't know too much syntax) but I want something like:
x = numbers in filename.txt
x -= 1
os.rename('current#.txt', 'x.txt')

How might I go about doing this?
Thanks

This script should work

import re, os

pattern = re.compile("(\+|\-)?\d+\.txt")

def find_name():
  folder = "C:/Users/Sam/Desktop"
  for filename in os.walk(folder).next()[2]:
    if pattern.match(filename):
      return filename

def main():
  filename = find_name()
  number = int(filename[:-4])
  newname = str(number-1) + ".txt"
  os.rename(filename, newname)
  print("file %s renamed %s" % (filename, newname))

main()

You could improve the idea by storing the date where you're going to leave high school and compute automatically the remaining number of days.

Wow, I wouldn't have figured that out any time soon; thanks a lot.

Edit: when you do 'return filename' at line 10, does filename become a global variable or enclosing?

No, it doesn't become a global variable. It's only a value returned by the function. This allows to write

variable = find_name()

and get this returned value.

What happens when you forget to run the script or your computer is off one day? I suppose that's one more day of school ;)

If you want to calculate the number of days, try something like this:

import datetime
graduation_date = datetime.date(2010,8,31)
today = datetime.date.today()
duration = graduation_date - today
print 'I am free in: ' + str(duration.days) + ' days'

I think the date is right unless you're in a far-away timezone. duration is of type timedelta if you want to see what other information you can get from it.

Here's a good reference for datetime: http://docs.python.org/library/datetime.html

Ok, I finally got around to trying to butcher these two scripts together but now I get two errors thrown at me and I can't understand why.
This is my (pathetic) attempt at combining the scripts posted above:

import datetime, re, os

pattern = re.compile("(\+|\-)?\d+\.txt")
end_date = datetime.date(2010,8,31)
today = datetime.date.today()
duration = end_date - today

def find_name():
	folder = "C:/Users/Sam/Desktop"
	for filename in os.walk(folder).next()[2]:
		if pattern.match(filename):
			return filename

def main():
	newname = str(duration) + ".txt"
	filename = find_name()
	os.rename(filename, newname)

main()

But I get the following errors:
Traceback (most recent call last):
File "C:\Users\Sam\Desktop\temp.py", line 19, in <module>
main()
File "C:\Users\Sam\Desktop\temp.py", line 17, in main
os.rename(filename, newname)
WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect

I have a feeling it's my lack of knowledge of Python syntax that's causing these errors. Can someone help me out here?

Try adding print statements to both functions. "None" means that no pattern match was found.

def find_name():
    folder = "C:/Users/Sam/Desktop"
    for filename in os.walk(folder).next()[2]:
        print "testing filename", filename
        if pattern.match(filename):
            print "find_name returning", filename
            return filename
 
def main():
    newname = str(duration) + ".txt"
    filename = find_name()
    print "filename returned is", filename
    ## comment the next line for now, until you get
    ## the program fixed
##    os.rename(filename, newname)

Then see the article here, especially the os.path.normpath() http://pythonconquerstheuniverse.blogspot.com/2008/06/python-gotcha-raw-strings-and.html (This question has been asked so many times that it seems no one will answer it anymore.)

I figured out what was wrong; it turns out I forgot to add the ".days" to the "duration" variable when I assigned it to "newname". Here's the code that works:

import datetime, re, os

pattern = re.compile("(\+|\-)?\d+\.txt")
end_date = datetime.date(2010,8,31)
today = datetime.date.today()
duration = end_date - today

def find_name():
	folder = "C:/Users/Sam/Desktop"
	for filename in os.walk(folder).next()[2]:
		if pattern.match(filename):
			return filename

def main():
	newname = str(duration.days) + ".txt"
	filename = find_name()
	os.rename(filename, newname)

main()

Thanks for helping though!

This question has already been answered. Start a new discussion instead.