Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
loop through files
#1
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))
Reply
#2
(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?
Reply
#3
What is the purpose of that 'pass' statement on line 11?
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Loop through all files in a directory? Winfried 10 257 8 hours ago
Last Post: FortuneCoins
  File loop curiously skipping files - FIXED mbk34 10 796 Feb-10-2024, 07:08 AM
Last Post: buran
  How to loop through all excel files and sheets in folder jadelola 1 4,490 Dec-01-2022, 06:12 PM
Last Post: deanhystad
  Using Python to loop csv files to open them Secret 4 2,727 Sep-13-2020, 11:30 AM
Last Post: Askic
  Loop through folder of Excel Files and extract single column fioranosnake 2 4,532 Oct-28-2019, 05:19 PM
Last Post: fioranosnake
  How can I sort my names of files in for loop? Mike Ru 2 2,536 Aug-02-2019, 04:56 AM
Last Post: perfringo
  Loop files - Extract List Data To Individual Columns in CSV dj99 5 3,272 May-19-2019, 10:29 AM
Last Post: dj99
  Delete Lines that Contain Words - Loop through files in a folder - Write to new files dj99 3 3,449 May-18-2019, 06:34 AM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020