我仍处于python的学习过程中。
我试图创建一个执行以下操作的脚本:
所以这就是我到目前为止:
import os, fnmatch
def findDir(path,filter):
for root, dirs, files in os.walk(path):
for file in fnmatch.filter(files, filter):
yield os.path.join(root, file)
for findDir中的pdfFile(r' C:\ new',' * .pdf'): 打印(pdfFile)
它遍历目录并在其中查找PDF。但现在我不知道如何继续。
非常感谢任何帮助!
我也对任何语法/拼写错误表示歉意。
答案 0 :(得分:0)
你的规格很模糊,所以我不得不承担很多事情。我认为这段代码可以达到您想要的效果,但您可能需要稍微调整一下(例如目录名中的日期格式)。
我假设了一个像这样的目录结构:
c:\new (base dir)
daily_2014_12_14
daily_2014_12_15
...
standard
代码:
import os
import fnmatch
import time
import shutil
import re
# directories
base_dir = "C:\new"
standard_dir = os.path.join(base_dir, "standard")
# find files in directory. based on yours, but modified to return a list.
def find_dir(path, name_filter):
result = []
for root, dirs, files in os.walk(path):
for filename in fnmatch.filter(files, name_filter):
result.append(os.path.join(root, filename))
return result
# getting today's directory. you can rearrange year-month-day as you want.
def todays_dir():
date_str = time.strftime("%Y_%m_%d")
return os.path.join(base_dir, "daily_" + date_str)
# copy a file from one directory to another
def copy(filename, from_dir, to_dir):
from_file = os.path.join(from_dir, filename)
to_file = os.path.join(to_dir, filename)
shutil.copyfile(from_file, to_file)
# main logic
today_dir = todays_dir()
pdfs = find_dir(today_dir, "*.pdf")
excels = find_dir(today_dir, "*.xls")
if len(pdfs) == 0:
copy("standard1.pdf", standard_dir, today_dir)
copy("standard2.pdf", standard_dir, today_dir)
if len(excels) == 1:
excel_name = os.path.splitext(excels[0])[0]
excel_num = re.findall(r"\d+", excel_name)[-1]
copy(excel_num + ".pdf", standard_dir, today_dir)
另外:我同意Iplodman的评论。下次再向我们展示一下。