Python Forum

Full Version: loop through files
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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))
(Apr-06-2018, 05:15 PM)Jrherbert Wrote: [ -> ]but it's not working
Please, do go on.

Does it do something it shouldn't? Is it supposed to do something it isn't? Is there an error? What's the error message?
What is the purpose of that 'pass' statement on line 11?