微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

遍历目录树并将日期戳附加到文件名

如何解决遍历目录树并将日期戳附加到文件名

我有一个大约900字左右的目录,excel,PDF文件,我的最终目标是我只想扫描目录中的PDF文档,将它们移动到单个文件中,给它们加上日期戳,然后为它们搜索某些公司名称,返回找到文本的文件名/日期戳。

我编写此代码的第一步是,首先通过去除不需要的内容/同时复制PDF文件来组织文件,同时重命名每个PDF文件以在每个文件名中包含创建日期。但是,我正在努力使这些基础知识起作用。到目前为止,这是我的代码,位于少数文件的测试目录上-到目前为止,我已将其设置为打印每个文件夹,子文件夹和文件名,以检查演练是否正常运行,并且可行:

import os
import datetime

os.chdir(r'H:\PyTest')

def modification_date(filename):
    t = os.path.getctime(filename)
    return datetime.datetime.fromtimestamp(t).year,datetime.datetime.fromtimestamp(t).month

#Test function works
modification_date(r'H:\PyTest\2010\Oct\Meeting Minutes.docx')
#output: (2020,10)
   
#for loop walks through the main folder,each subfolder and each file and prints the name of each pdf file found
for folderName,subfolders,filenames in os.walk('H:\PyTest'):
    print ('the current folder is ' + folderName)
    
    for subfolder in subfolders:
        print('SUBFOLDER OF ' + folderName + ':' + subfolder)
    
    for filename in filenames:
        if filename.endswith('pdf'):
            print(filename)
            #print(modification_date(filename))

最后我没有注释print(modification_date(filename),这似乎可以打印出所有pdf的目录和名称

the current folder is H:\PyTest
SUBFOLDER OF H:\PyTest:2010
SUBFOLDER OF H:\PyTest:2011
SUBFOLDER OF H:\PyTest:2012
the current folder is H:\PyTest\2010
SUBFOLDER OF H:\PyTest\2010:Dec
SUBFOLDER OF H:\PyTest\2010:Oct
the current folder is H:\PyTest\2010\Dec
HF Cheat Sheet.pdf
the current folder is H:\PyTest\2010\Oct
the current folder is H:\PyTest\2011
SUBFOLDER OF H:\PyTest\2011:Dec
SUBFOLDER OF H:\PyTest\2011:Oct
the current folder is H:\PyTest\2011\Dec
HF Cheat Sheet.pdf
the current folder is H:\PyTest\2011\Oct
the current folder is H:\PyTest\2012
SUBFOLDER OF H:\PyTest\2012:Dec
SUBFOLDER OF H:\PyTest\2012:Oct
the current folder is H:\PyTest\2012\Dec
HF Cheat Sheet.pdf
the current folder is H:\PyTest\2012\Oct

但是,在我的代码中包含print(modification_date(filename)时,出现FileNotFound错误。因此,似乎该函数不知道目录路径,这就是它失败的原因。

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'HF Cheat Sheet.pdf'

任何人都可以建议编辑如何获取日期戳,然后更改每个pdf名称以将其包括在开头或结尾吗?我正在寻找文件的上次保存日期。

非常感谢

解决方法

您必须使用var folderName来构造文件的完整路径。会是这样的:

for folderName,subfolders,filenames in os.walk('H:\PyTest'):
    print ('the current folder is ' + folderName)
    
    for subfolder in subfolders:
        print('SUBFOLDER OF ' + folderName + ':' + subfolder)
    
    for filename in filenames:
        if filename.endswith('pdf'):
            print(filename)
            print(modification_date(os.path.join(folderName,filename)))

folderName中(通常将此变量称为root),存储的是路径 from :您放置在os.walk()中的路径:迭代中的当前文件夹。要获取文件的完整路径,必须将其与文件名连接起来。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。