我有一个大约 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 名称以将其包含在开头或结尾?我正在查找文件上次保存的日期。
非常感谢