Python: 重命名以“#”开头的多个文件

Python: Rename multiple files starting with a "#"

我想重命名目录中的多个文件,如果它们以“#”开头,例如:

#222_message_split -> 222_message_split

#013_message_split2 -> 013_message_split2

编辑:我试过这个:

for filename in os.listdir(PATH):
    if filename.startswith("#"):
        os.rename(filename, filename[1:])

edit2:在 pstatix 的帮助下,我的代码开始工作,现在也在检查子目录中的“#_____”文件。

for root, dirs, files in os.walk(PATH):
for dir in dirs:
    if dir.startswith("#"):
        org_fp = os.path.join(root, dir)
        new_fp = os.path.join(root, dir[1:])
        os.rename(org_fp, new_fp)

你很接近,虽然你的缩进是关闭的:

原题:

for filename in os.listdir(PATH):
    if filename.startswith("#"):
        org_fp = os.path.join(PATH, filename)
        new_fp = os.path.join(PATH, filename[1:])
        os.rename(org_fp, new_fp)

os.listdir() 不是 return 完整路径,即使 PATH 是完整路径;仅列出基本名称。所以你必须为 os.rename() 提供完整路径才能正常运行;使用 os.path.join().

完成

评论请求更新:

for root, dirs, files in os.walk(PATH):
    for file in files:
        if file.startswith("#"):
            org_fp = os.path.join(root, file)
            new_fp = os.path.join(root, file[1:])
            os.rename(org_fp, new_fp)

查看 docs and this post 了解信息。