【问题标题】:Python WindowsError: [Error 3] The system cannot find the file specified when trying to renamePython WindowsError: [错误3] 尝试重命名时系统找不到指定的文件
【发布时间】:2012-02-09 23:00:57
【问题描述】:

我不知道出了什么问题。我之前用过rename没有任何问题,在其他类似问题中找不到解决方案。

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

【问题讨论】:

  • 好吧,path 中的os.rename(path, string) 是什么,它存在吗?
  • 扩展名不必为 3 个字符,因此请使用 os.path.splitext 表示该部分。
  • 顺便说一句效率更高:string = ''.join( random.sample(alphabet, random.randint(5,15)) )
  • 我认为您应该扩展 @Hamish 的建议,向我们展示您的目录结构的输出并在 os.rename 之前添加一个打印语句
  • 更好的变量名在这里会产生很大的不同。路径和字符串很差。请改用 src 和 dest。

标签: python


【解决方案1】:

您的代码中有一些奇怪的东西。例如,您的文件源是完整路径,但您要重命名的目标只是一个文件名,因此文件将出现在任何工作目录中 - 这可能不是您想要的。

您无法防止两个随机生成的文件名相同,因此您可以通过这种方式破坏您的一些数据。

试试这个,它应该可以帮助您发现任何问题。这只会重命名文件,并跳过子目录。

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】:

    如果您想保存回同一个目录,您需要为您的“字符串”变量添加一个路径。目前它只是创建一个文件名,而 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= ""
    

    【讨论】:

    • 将 for 循环切换为使用更有效的列表 comp 以获得对 OP 的最佳建议,而且您的代码中也存在缩进错误
    • @jdi 跑步前走路。在程序正确之前不要担心性能。在这里也完全不是问题。想想 os.rename 消耗了多少时钟?!您可以以任何方式编写此代码,并且 os.rename 将确定经过的时间。正确性始终是最重要的目标。
    • @DavidHeffernan - 我不同意。虽然这显然只是一种观点。我认为在给出答案的同时纠正惯用问题也很好。循环和添加字符串是绝对应该解决的问题,以帮助 OP 在 python 中成长。因为它,我投票赞成这个答案。
    • @jdi 我认为一些调试技能是接下来要学习的东西。但后来我们不同意。
    • 然而,先生,我仍然尊重你! :-)
    猜你喜欢
    • 2014-02-13
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 2020-06-24
    • 2014-04-12
    相关资源
    最近更新 更多