【发布时间】:2018-04-19 04:57:18
【问题描述】:
我正在尝试打印以单词 first 开头的文件名。
这是我所做的:
导入操作系统 重新导入
path = '/my_path'
for root, dirs, files in os.walk(path):
for file in files:
match_pattern = re.search(r'^first', file)
print match_pattern.group()
但是,这是我在运行程序时得到的:
first
Traceback (most recent call last):
File "test.py", line 10, in <module>
print match_pattern.group()
AttributeError: 'NoneType' object has no attribute 'group'
我想打印出以first开头的文件名,例如:
first-xyz
first abc
我做错了什么?
【问题讨论】:
-
match_pattern是None表示您的正则表达式与文件名不匹配。为什么不使用调试器,看看file的值是多少? -
我尝试打印出“文件”并返回了文件名
-
你为什么要为此使用正则表达式?只需使用
str.startswith。