[Tutor] (no subject)

Cameron Simpson cs at cskk.id.au
Fri Mar 22 21:04:39 EDT 2019


On 22Mar2019 17:45, Matthew Herzog <matthew.herzog at gmail.com> wrote:
>I have a Python3 script that reads the first eight characters of every
>filename in a directory in order to determine whether the file was created
>before or after 180 days ago based on each file's name. The file names all
>begin with YYYYMMDD or erased_YYYYMMDD_etc.xls. I can collect all these
>filenames already.
>I need to tell my script to ignore any filename that does not conform to
>the standard eight leading numerical characters, example: 20180922 or
>erased_20171207_1oIkZf.so.
>Here is my code.
>
>if name.startswith('scrubbed_'):
>            fileDate = datetime.strptime(name[9:17], DATEFMT).date()
>        else:
>            fileDate = datetime.strptime(name[0:8], DATEFMT).date()
>
>I need logic to prevent the script from 'choking' on files that don't fit
>these patterns. The script needs to carry on with its work and forget about
>non-conformant filenames. Do I need to add code that causes an exception or
>just add an elif block?

Just an elif. Untested example:

  for name in all_the_filenames:
    if name.startswith('erased_') and has 8 digits after that:
        extract date after "erased" ...
    elif name starts with 8 digits:
        extract date at the start
    else:
      print("skipping", repr(name))
      continue
    ... other stuff using the extracted date ...

The "continue" causes execution to go straight to the next loop 
iteration, effectively skipping the rest of the loop body. An exception 
won't really do what you want (well, not neatly).

Alan's suggestion of a regexp may be a sensible way to test filenames 
for conformance to your rules. \d{8} matches 8 digits. It doesn't do any 
tighter validation such as sane year, month or day values: 99999999 
would be accepted. Which may be ok, and it should certainly be ok for 
your first attempt: tighten things up later.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list