File: ifiles.py

package info (click to toggle)
python-dbfread 2.0.7-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 384 kB
  • sloc: python: 1,146; makefile: 140
file content (61 lines) | stat: -rw-r--r-- 1,346 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""
Functions for dealing with mixed-case files from case-preserving file
systems.

Todo:

  - handle patterns that already have brackets
"""

from __future__ import print_function
import os
import glob
import fnmatch


def ipat(pat):
    """Convert glob pattern to case insensitive form."""

    (dirname, pat) = os.path.split(pat)

    # Convert '/path/to/test.fpt' => '/path/to/[Tt][Ee][Ss][Tt].[]' 
    newpat = ''
    for c in pat:
        if c.isalpha:
            u = c.upper()
            l = c.lower()
            if u != l:
                newpat = newpat + '[' + u + l + ']'
            else:
                newpat += c
        else:
            newpat += c

    newpat = os.path.join(dirname, newpat)

    return newpat

def ifnmatch(name, pat):
    """Case insensitive version of fnmatch.fnmatch()"""
    return fnmatch.fnmatch(name, ipat(pat))

def iglob(pat):
    """Case insensitive version of glob.glob()"""
    return glob.glob(ipat(pat))

def ifind(pat, ext=None):
    """Look for a file in a case insensitive way.

    Returns filename it a matching file was found, or None if it was not.
    """

    if ext:
        pat = os.path.splitext(pat)[0] + ext

    files = iglob(pat)
    if files:
        return files[0]  # Return an arbitrary file
    else:
        return None

__all__ = ['ipat', 'ifnmatch', 'iglob', 'ifind']