Apr-06-2018, 05:15 PM
Trying to loop through files in a directory, open the files that contain a certain string in the file name, and then edit those files. Here is what I've got but it's not working
import os import glob import re import datetime as dt OldValue = input('Enter the value to be replaced: ') NewValue = input('Enter the replacement value: ') location = input('Enter path to directory: ') pattern = os.path.join(location,'PMPM*') for matching_file in glob.glob(pattern): with open(matching_file, 'r') as f: pass read_file = f.read() regex = re.compile(OldValue) read_file = regex.sub(NewValue, read_file) write_file = open(read_file, 'w') write_file.write(read_file) now = dt.datetime.now() ago = now - dt.timedelta(minutes=30) for root, dirs, files in os.walk('.'): for fname in files: path = os.path.join(root, fname) st = os.stat(path) mtime = dt.datetime.fromtimestamp(st.st_mtime) if mtime > ago: print('%s modified %s' % (path, mtime))