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

前端 未结 2 614
没有蜡笔的小新
没有蜡笔的小新 2021-01-20 19:09

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 ran         


        
相关标签:
2条回答
  • 2021-01-20 19:19

    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)
    
    0 讨论(0)
  • 2021-01-20 19:21

    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= ""
    
    0 讨论(0)
提交回复
热议问题