在单个目录中批量重命名文件时找不到指定的文件

时间:2015-03-30 20:09:15

标签: python media rename

我已经创建了一个简单的脚本来重命名我的媒体文件,这些文件有许多奇怪的时期和内容,我已经获得并希望进一步组织。我的脚本有点工作,我将编辑它以进一步编辑文件名,但我的os.rename行引发了这个错误:

[Windows错误:错误2:系统找不到指定的文件。]

import os
for filename in os.listdir(directory):
    fcount = filename.count('.') - 1              #to keep the period for the file extension
    newname = filename.replace('.', ' ', fcount)
    os.rename(filename, newname)

有谁知道为什么会这样?我有一种感觉,它不像我试图重命名文件而不包括文件路径?

3 个答案:

答案 0 :(得分:1)

os.rename(filename, directory + '/' + newname);

答案 1 :(得分:1)

Triton Man已经回答了你的问题。如果他的答案不起作用,我会尝试使用绝对路径而不是相对路径。

之前我做过类似的事情,但为了防止任何名称冲突发生,我暂时将所有文件移动到子文件夹中。整个过程发生得如此之快,以至于在Windows资源管理器中我从未看到子文件夹被创建。

无论如何,如果您对查看我的脚本感兴趣,请参阅下面的内容。您在命令行上运行脚本,您应该作为命令行参数传入要重命名的jpg文件的目录。

这是我用来将.jpg文件重命名为10的倍数的脚本。查看它可能很有用。

'''renames pictures to multiples of ten'''
import sys, os

debug=False

try:
    path = sys.argv[1]
except IndexError:
    path = os.getcwd()

def toint(string):
    '''changes a string to a numerical representation
    string must only characters with an ordianal value between 0 and 899'''
    string = str(string)
    ret=''
    for i in string:
        ret += str(ord(i)+100) #we add 101 to make all the numbers 3 digits making it easy to seperate the numbers back out when we need to undo this operation
    assert len(ret) == 3 * len(string), 'recieved an invalid character. Characters must have a ordinal value between 0-899'
    return int(ret)

def compare_key(file):
    file = file.lower().replace('.jpg', '').replace('dscf', '')
    try:
        return int(file)
    except ValueError:
        return toint(file)

#files are temporarily placed in a folder
#to prevent clashing filenames
i = 0
files = os.listdir(path)
files = (f for f in files if f.lower().endswith('.jpg'))
files = sorted(files, key=compare_key)
for file in files:
    i += 10
    if debug: print('renaming %s to %s.jpg' % (file, i))
    os.renames(file, 'renaming/%s.jpg' % i)

for root, __, files in os.walk(path + '/renaming'):
    for file in files:
        if debug: print('moving %s to %s' % (root+'/'+file, path+'/'+file))
        os.renames(root+'/'+file, path+'/'+file)

编辑:我摆脱了所有的jpg绒毛。您可以使用此代码重命名文件。只需更改rename_file函数即可删除多余的点。我还没有对此代码进行测试,因此可能无法正常运行。

import sys, os

path = sys.argv[1]

def rename_file(file):
    return file

#files are temporarily placed in a folder
#to prevent clashing filenames
files = os.listdir(path)
for file in files:
    os.renames(file, 'renaming/' + rename_file(file))

for root, __, files in os.walk(path + '/renaming'):
    for file in files:
        os.renames(root+'/'+file, path+'/'+file)

答案 2 :(得分:0)

看起来我只需要设置默认目录,它就可以了。

folder = r"blah\blah\blah"    
os.chdir(folder)
for filename in os.listdir(folder):
    fcount = filename.count('.') - 1
    newname = filename.replace('.', ' ', fcount)
    os.rename(filename, newname)