我需要在特定日期创建的所有子文件夹中找到所有文本文件,将其打开,然后将内容复制到单个文本文件中

黑马饺子

在此处输入图片说明

我的目标是将所有文本文件的内容放在今天创建的子文件夹中,并将它们移动到单个现有的report.txt中,但是我似乎找不到解决该问题的好方法。我在编码方面不是很有经验,所以将不胜感激。这是到目前为止我所拥有的(我知道这是垃圾):

if getmtime == today:
   with open(glob.iglob(drive + "://CADIQ//CADIQ_JOBS//?????????????????????")) as f:
      for line in f:
         content += line
   with open(reportFile, "a") as f:
      f.write(content)
铁匠

根据如何列出目录的所有文件来尝试此操作?

import os, time

def last_mod_today(path):
    '''
    return True if getmtime and time have year, mon, day coincinding in their localtime struct, False else
    '''
    t_s = time.localtime(os.path.getmtime(path))
    today = time.localtime(time.time())
    return t_s.tm_mday==today.tm_mday and t_s.tm_year == today.tm_year and t_s.tm_mon == today.tm_mon

name_to_path = lambda d,x:os.path.normpath(os.path.join(os.path.join(os.getcwd(), d),x))

def log_files(d):
    '''
    walking through the files in d
    log the content of f when last modif time for f is today
    WARNING : what happens when the file is a JPEG ?
    '''
    scand_dir = os.path.join(os.getcwd(), d)
    print(f"scanning {scand_dir}...")
    (_, _, filenames) = next(os.walk(scand_dir))
    log = open("log.txt", 'a')
    for f in filenames:
        if last_mod_today(name_to_path(d,f)):
            with open(name_to_path(d,f), 'r') as todays_file:
                log.write('##############################\n')
                log.write(f"file : {name_to_path(d,f)}\n")
                log.write(todays_file.read()) 
                log.write('\n')
                log.write('##############################\n')
    log.close()

#first scanning files in the current directory
(_, dirnames, _) = next(os.walk('./'))
log_files('./')
#then crawling through the subdirs (one level)
for d in dirnames:
    log_files(d)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章