0

enter image description here

My goal is to take the contents of all text files in subfolders created today and move them to a single existing report.txt but I can't seem to find a good way to go about it. I'm not very experienced in coding so any help would be much appreciated. Here is what I have so far (I know it's rubbish):

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)

3 Answers3

1

I would start by creating a desired_date object, which is a datetime.date. You can then format that date into a string, which makes up the pattern you want to look for in your glob. The glob pattern doesn't care about the time, just the date.

from pathlib import Path
import datetime

desired_date = datetime.date(year=2020, month=12, day=22)
pattern = "13.2.1_" + desired_date.strftime("%y_%m_%d") + "_*"

for path in Path("path/to/folders").glob(pattern):
    if not path.is_dir():
        continue
    print(path)

From there, you can visit each path, glob all text files in the current path, and accumulate the lines in each text file. Finally, write everything to one file.

Paul M.
  • 10,481
  • 2
  • 9
  • 15
1
import glob

contents = b''
for file in glob.glob('./*/*.txt'): # u can change as per your directory
    fname = file.split(r'\\')[-1]
    with open(fname, 'rb') as f1:
        contents += f1.read()
with open('report.txt','wb') as rep:
    rep.write(contents)

Hope this helps so :) Better try to read or write files in terms of bytes because sometimes there may be a chance of corrupting data.

Nanthakumar J J
  • 860
  • 1
  • 7
  • 22
1

Try this, based on How do I list all files of a directory?

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)
smed
  • 148
  • 1
  • 10