如何使用重命名功能

时间:2018-12-24 10:22:45

标签: python

这是我得到的错误:

  

系统找不到指定的文件:'1.jpg'->'0.jpg'

即使我在目录中也有一个名为1.jpg的文件。

我正在制作文件重命名脚本,该脚本重命名给定目录中的所有文件,并给每个文件增加一个数字+1。

 import { createStore, applyMiddleware, compose } from "redux";
 import rootReducer from "../reducers/index";
 import { forbiddenWordsMiddleware } from "../middleware";

 const storeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || 
 compose;

 const store = createStore(
   rootReducer,
   storeEnhancers(applyMiddleware(forbiddenWordsMiddleware))
 );
 export default store;

应该将所有文件重命名为“ 0.jpg”,“ 1.jpg”等

2 个答案:

答案 0 :(得分:1)

代码:

import os


def moving_script():
    directory = input("Give the directory")
    xlist = os.listdir(directory)
    counter = 0

    for files in xlist:
        os.rename(os.path.join(directory, files),
                  os.path.join(directory, str(counter)+".jpg"))
        counter = counter + 1


if __name__ == '__main__':
    moving_script()

结果:

~/Documents$ touch file0 file1 file2 file3 file4


ls ~/Documents/
file0  file1  file2  file3  file4


$ python renamer.py
Give the directory'/home/suser/Documents'

$ ls ~/Documents/
0.jpg  1.jpg  2.jpg  3.jpg  4.jpg

答案 1 :(得分:0)

os.listdir()将返回文件名,但不包含路径。因此,当您将files传递给os.rename()时,它是在当前工作目录中查找它,而不是它们所在的目录(即由用户提供)。

import os

def moving_script():
    directory = input("Give the directory")
    counter = -1
    for file_name in os.listdir(directory):
        old_name = os.path.join(directory, file_name)
        ext = os.path.splitext(file_name)[-1] # get the file extension
        while True:
            counter += 1
            new_name = os.path.join(directory, '{}{}'.format(counter, ext))
            if not os.path.exists(new_name):
                os.rename(old_name, new_name)
                break

moving_script()

请注意,此代码检测文件扩展名是什么。在您的代码中,您可以重命名扩展名为.jpg的非jpg文件。为避免这种情况,您可以将os.listdir(directory)更改为glob.glob(os.path.join(directory, *.jpg')),它将仅对'* .jpg'文件进行迭代。不要忘记您需要导入glob,并且在Linux上也区分大小写,因此'* .jpg'不会返回'* .JPG'文件

编辑:代码已更新以检查新文件名是否已存在。