重命名 Python 中的所有文件名

Rename all files's name in Python

# -*- coding:utf-8-*-

import os
import time
import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("version", help="Enter your package version")
    args = parser.parse_args()

    rootdir = os.getcwd()
    list = os.listdir(rootdir)

    #default version = 1.1.0
    version = '1.1.0'
    if args.version:
        version = args.version

    for line in list:
        times = time.strftime("%Y%m%d",time.localtime())
        list = ['ABCD', 'android', version, 'abcd', times]
        st = '_'
        result = st.join(list) + '.apk'

        origin_file = os.path.join(rootdir, line)
        print(origin_file)
        new_file = os.path.join(rootdir, result)
        print(new_file)
        os.rename(origin_file, new_file)

if __name__ == "__main__":
   main()

正在尝试将所有文​​件重命名为脚本后目录中的特定名称。

然而,这里的错误:

Traceback (most recent call last):

File "rename-apk.py", line 31, in

os.rename(origin_file, new_file)

OSError: [Errno 20] Not a directory

我猜你正在使用 Pycharm ,.idea 文件夹是 per documentation -

Project Settings

Project settings are stored with each specific project as a set of xml files under the .idea folder. If you specify the default project settings, these settings will be automatically used for each newly created project.

(强调我的)

Files/Folders 以 . 开头的名称默认隐藏。

无论如何,.idea 文件夹不是问题所在。如果您尝试重命名任何其他目录,也会出现此问题。

问题的发生主要是因为您创建文件名的方式,您使用的 times 在整个程序执行过程中都是不变的,因为您只取年、月和日。

基本上,您正在为列表中的每个文件创建完全相同的结果名称。

您收到的错误是因为您将其他内容重命名为 - ABCD_android_1.1.22_abcd_20150903.apk ,这是一个文件。

然后您尝试将 .idea(这是一个目录)重命名为 ABCD_android_1.1.22_abcd_20150903.apk,这原本是一个文件,因为这是不可能的,您会得到错误 - Not a Directory .

你甚至可能丢失了很多 .apk ,因为 os.rename 的工作原理 -

Rename the file or directory src to dst. If dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission.

(强调我的)

您应该以某种方式为每个 .apk 创建唯一的 file_names 。也许您也可以在新文件名中包含原始文件名,或者您应该将时间戳记为微秒(您可以为此使用 datetime 模块,并在其中使用 %f 微秒格式)(即使这样,如果计算机运行 太快了,你可能 运行 进入这个问题或得到错误)。

此外,您可能不想替换所有文件,如果是这样,您应该考虑添加一些条件来检查要替换哪些文件。例如,如果您只想重命名 .apk 个文件,则可以添加一个条件,如 -

if line.endswith('.apk'):

作为 for 循环内的第一行,以及此 if 块内的其余代码。

此外,您可能不想使用 list 作为变量名,因为它会遮盖内置函数 list() 。而且您不应该像现在使用 list 一样重复使用相同的变量名。