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

I can’t understand what happened. I used renaming without problems and cannot find a solution to other similar issues.

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= ""
+2
source share
2 answers

There are some strange things in the code. For example, your file source is the full path, but your destination for renaming is just the file name, so the files will appear in any working directory, which is probably not the way you wanted.

You have no protection against two randomly generated file names that are the same, so you can destroy some of your data this way.

, . .

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)
+2

, "string". , os.rename .

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= ""
+2

Source: https://habr.com/ru/post/1605664/


All Articles