0

我正在尝试重命名目录中的所有文件,对每个文件进行多次更改,以使文件名对互联网友好。它适用于一些替换,然后它说找不到文件。我虽然如果我放慢它的速度time.sleep()会起作用,但这似乎没有效果(除了变慢)。在某些情况下,我可以多次运行脚本并完成目标,但在某些情况下,它完成时没有错误,但没有进行更改。任何建议,将不胜感激。

import os, glob, time
path  = os.getcwd()
dirlist = glob.glob('*.pdf')
for filename in dirlist:
    os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(' ', '_')))
    os.rename(os.path.join(path, filename), os.path.join(path, filename.lower().encode('utf8')))
    os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(' (', '-')))
    os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(')', '')))
    os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(',', '')))
    os.rename(os.path.join(path, filename), os.path.join(path, filename.replace('_-_', '-')))
4

2 回答 2

3

filename.replace()返回一个新字符串 - 它不会以任何方式更改文件名。所以文件名在重命名文件后会过时,并在下次使用时导致文件未找到错误。

尝试这样的事情:

import os, glob, time

def new_filename(filename):
    return filename.replace(' ', '_').lower().encode('utf8').replace(' (', '-') \
                   .replace(')', '').replace(',', '').replace('_-_', '-')

path  = os.getcwd()
dirlist = glob.glob('*.pdf')
for filename in dirlist:
    os.rename(os.path.join(path, filename), os.path.join(path, new_filename(filename)))
于 2013-05-25T06:02:33.777 回答
0
usage = '''

$python slug_dir.py DIR

'''

from os import rename, walk
from os.path import join, isdir, splitext
from slugify import slugify


def rename_files(dir_path):
    for path, subdirs, files in walk(dir_path):
        for fname in files:
            filename, extension = splitext(fname)
            s = slugify(filename)
            newname = s+extension
            try:
                oldpath = join(path, fname)
                newpath = join(path, newname)
                print rename(oldpath, newpath)
                print 'Rename: ', oldpath, '->', newpath
            except Exception as e:
                print 'Error triying rename: ', fname, '->', newname
                raise e

def main():

    dirname = sys.argv[1]
    if not isdir(dirname):
        print usage
        sys.exit(1)

    rename_files(dirname)


if __name__ == '__main__':
    main()
于 2016-11-08T23:03:58.120 回答