2012-02-09 67 views
2

我无法弄清楚什么是错时指定的文件。我之前使用过重命名,没有任何问题,并且在其他类似问题中找不到解决方案。的Python WindowsError:[错误3]系统找不到尝试重新命名

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

那么,'os.rename(path,string)'中的'path'是否存在? – Hamish 2012-02-09 23:03:20

+2

扩展名不一定是3个字符,因此对该部分使用'os.path.splitext'。 – wim 2012-02-09 23:08:44

+0

这是更有效的BTW:'字符串=“”。加入(random.sample(字母,random.randint(5,15)))' – jdi 2012-02-09 23:15:09

回答

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) 
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= "" 
+0

切换为循环使用,用于向OP最好的建议更有效的列表比较,还必须在运行之前,你的代码 – jdi 2012-02-09 23:21:18

+0

@jdi步行缩进错误。在程序正确之前不要担心perf。这里完全没有问题。想想os.rename有多少时钟?你可以用任何方式编写这段代码,os.rename将决定经过的时间。正确性始终是最重要的目标。 – 2012-02-09 23:26:31

+0

@DavidHeffernan - 我不同意。虽然这显然只是一个意见。我认为在给出答案的同时还要纠正习惯问题。循环和添加字符串是一定要解决的,以帮助OP在python中成长。因为这个,我正在投票回答这个问题。 – jdi 2012-02-09 23:29:02

相关问题