whwright
whwright

Reputation: 561

Python WindowsError: [Error 3] The system cannot find the file specified when trying to rename

I can't figure out what's wrong. I've used rename before without any problems, and can't find a solution in other similar questions.

import os
import random

directory = "C:\\whatever"
string = ""
alphabet = "abcdefghijklmnopqrstuvwxyz"


listDir = os.listdir(directory)

for item in listDir:
    path = os.path.join(directory, item)

    for x in random.sample(alphabet, random.randint(5,15)):
        string += x

    string += path[-4:] #adds file extension

    os.rename(path, string)
    string= ""

Upvotes: 3

Views: 26333

Answers (2)

timc
timc

Reputation: 2174

If you want to save back to the same directory you will need to add a path to your 'string' variable. Currently it is just creating a filename and os.rename requires a path.

for item in listDir:
    path = os.path.join(directory, item)

    for x in random.sample(alphabet, random.randint(5,15)):
        string += x

    string += path[-4:] #adds file extension
    string = os.path.join(directory,string)

    os.rename(path, string)
    string= ""

Upvotes: 2

wim
wim

Reputation: 363596

There are a few strange things in your code. For example, your source to the file is the full path but your destination to rename is just a filename, so files will appear in whatever the working directory is - which is probably not what you wanted.

You have no protection from two randomly generated filenames being the same, so you could destroy some of your data this way.

Try this out, which should help you identify any problems. This will only rename files, and skip subdirectories.

import os
import random
import string

directory = "C:\\whatever"
alphabet = string.ascii_lowercase

for item in os.listdir(directory):
  old_fn = os.path.join(directory, item)
  new_fn = ''.join(random.sample(alphabet, random.randint(5,15)))
  new_fn += os.path.splitext(old_fn)[1] #adds file extension
  if os.path.isfile(old_fn) and not os.path.exists(new_fn):
    os.rename(path, os.path.join(directory, new_fn))
  else:
    print 'error renaming {} -> {}'.format(old_fn, new_fn)

Upvotes: 2

Related Questions