python re.search error TypeError: expected string or buffer
Asked Answered
M

2

5

Why would

re.search("\.docx", os.listdir(os.getcwd()))

yield the following error?

TypeError: expected string or buffer

Moorwort answered 6/4, 2014 at 16:41 Comment(0)
P
10

Because os.listdir returns a list but re.search wants a string.

The easiest way to do what you are doing is:

[f for f in os.listdir(os.getcwd()) if f.endswith('.docx')]

Or even:

import glob
glob.glob('*.docx')
Pend answered 6/4, 2014 at 16:43 Comment(1)
Thanks for being gentle, I just started python today! Thank you!Moorwort
B
2

re.search() expects str as the second argument. Refer docs to know more.

import re, os

a = re.search("\.docx", str(os.listdir(os.getcwd())))
if a:
    print(True)
else:
    print(False)
Becka answered 6/4, 2014 at 16:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.