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

2024-10-06 08:08:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

Tags: tointodaysoismyaswith
3条回答

我首先创建一个desired_date对象,它是一个datetime.date。然后,您可以将该日期格式化为一个字符串,该字符串构成您希望在glob中查找的模式。全球模式不在乎时间,只在乎日期

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)

从那里,您可以访问每个路径,对当前路径中的所有文本文件进行全局搜索,并累积每个文本文件中的行。最后,将所有内容写入一个文件

试试这个,基于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)
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)

希望这有帮助:) 最好尝试以字节为单位读取或写入文件,因为有时可能会损坏数据

相关问题 更多 >