【问题标题】:Unable to rename the last file of the directory using loop无法使用循环重命名目录的最后一个文件
【发布时间】:2021-04-21 18:35:31
【问题描述】:

我正在开发一个重命名功能,该功能根据媒体创建日期为视频文件编制索引。由于媒体创建日期不是文件元数据,我正在使用 win32com.propsys 模块,它完全按预期工作,直到FILES 列表的最后一个元素,但进入剩余文件的循环。我无法抓住这个问题。非常感谢您提出积极的建议。

import os
import pytz
import datetime
from win32com.propsys import propsys, pscon
os.chdir(r'H:\Study material\Python\practice')
current_path = r'H:\Study material\Python\practice'
files = os.listdir(current_path)
fi = []
li = []
for f in files:
    properties = propsys.SHGetPropertyStoreFromParsingName(r'H:\Study material\Python\practice'+'\\'+f )
    d = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue()
    fi.append([str(d),f])
fi.sort()
l = [s[1] for s in fi]
for f in files:
    i = l.index(f) + 1
    new_name = str(i)+'-'+ f
    li.append(new_name)
i = 0
for f in files:
    os.rename(f,li[i])
    i+=1

【问题讨论】:

    标签: python windows rename


    【解决方案1】:

    我猜排序文件列表中的最后一项是目录(可能是 '__pycache__' ?)。尝试检查它是否真的是一个文件:

    ...
    for f in files:
        if not os.path.isfile(f):
            print(f'not a file: {f}')
            continue
        properties = propsys.SHGetPropertyStoreFromParsingName(
            os.path.join(r'H:\Study material\Python\practice', f) )
        d = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue()
        fi.append([str(d), f])
    ...
    

    或者尝试打印每个文件名和新名称,看看是否一切正确:

    ...
    for i, f in enumerate(files):
        print(f, 'rename to', li[i])
        os.rename(f, li[i])
    

    【讨论】:

    • 该目录包含 7 个文件...它重命名了 6 个文件,但在 7 个文件中的 1 个随机文件中循环...。循环继续到 的倒数第二行使用rename()
    • @VishwajeetBhagat 可能存在隐藏文件和文件夹。我已经更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    相关资源
    最近更新 更多