1

I have a directory (client_dir) with a folder that is named "XXX - Long client name"

I want to save the full name of the folder ("XXX - Long client name") as a variable called client_name. I can search for "XXX - Long client name" by matching the first 3 characters (XXX).I get the 3 characters somewhere else.

I tried using the re modudule, but I can't figure out how to get the actual full string. It only returns "XXX".

for closeout in os.listdir(closeout_dir):
    project_id = closeout[:8]
    client = project_id[0:3] 
    for x in os.listdir(client_dir):
        client_name = re.search(client,x)

    print(client_name)
    print(type(client_name))

output:

<re.Match object; span=(0, 3), match='XXX'>
<class 're.Match'>
XXX

Another problem I've encountered is that when I add another folder to client_dir called "YYY- another client name" it can't find my "XXX - Long client name" folder anymore. The output is:

None
<class 'NoneType'>
alex
  • 11
  • 1
  • 1
    Please post a [mcve]. – user202729 Feb 12 '21 at 02:03
  • Almost [python - Convert SRE_Match object to string - Stack Overflow](https://stackoverflow.com/questions/23025565/convert-sre-match-object-to-string) – user202729 Feb 12 '21 at 02:06
  • 1
    Although in this case you probably don't need a regex at all, just use [Does Python have a string 'contains' substring method? - Stack Overflow](https://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method) – user202729 Feb 12 '21 at 02:08
  • check like this `if closeout[:3] == 'XXX': long_client_name = closeout[6:]`. This should solve your problem – Joe Ferndz Feb 12 '21 at 02:30

1 Answers1

0
for closeout in os.listdir(closeout_dir):
    project_id = closeout[:8]
    client = project_id[0:3]
    for x in os.listdir(client_dir):
        client_name = re.search(client,x)
        print(x)                # Actual full string
        print(client_name)
        print(type(client_name))
  1. See my code, x is actual full string, no need to return it in re.search.
  2. And you need to indent print statement to run it in a for loop. If you dont indent it, you will only print last value of for loop.
ion ling
  • 11
  • 1