Python WindowsError: [错误 3] 系统找不到指定的文件,尝试重命名时

3 投票
2 回答
26126 浏览
提问于 2025-04-17 12:43

我搞不清楚哪里出错了。我之前用过重命名功能,一直没问题,现在在其他类似的问题中也找不到解决办法。

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 个回答

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

你的代码里有一些奇怪的地方。例如,你指定的文件源是完整路径,但你重命名的目标只是一个文件名,这样文件会出现在当前工作目录里——这可能不是你想要的结果。

另外,你没有处理两个随机生成的文件名可能相同的情况,这样可能会导致你的一些数据被覆盖。

试试这个代码,它可以帮助你找出问题。这个代码只会重命名文件,而不会处理子目录。

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)

撰写回答