Python re.search error TypeError: expected string or buffer

Why

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

print the following error?

TypeError: expected string or buffer

+4
source share
2 answers

Because it os.listdirreturns list, but re.searchwants a string.

The easiest way to do what you do:

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

Or even:

import glob
glob.glob('*.docx')
+9
source

re.search()expects stras the second argument. Contact docs to find out more.

import re, os

a = re.search("\.docx", str(os.listdir(os.getcwd())))
if a:
    print(True)
else:
    print(False)
+2
source

Source: https://habr.com/ru/post/1535260/


All Articles