Reputation: 35
I am trying to print the filename 'xyz.0.html
' in the console. It is spitting out an error "substring not found"
files in directory:
xyz.0.html
xyz.1.html
xyz.2.html
python
for name in glob.glob('*html'):
if name.index('.0.html'):
print name
Upvotes: 2
Views: 4943
Reputation: 4481
you can use python's generator
print [name for name in glob.glob('*html') if name.endswith(".0.html")]
Upvotes: 0
Reputation: 35947
Why not use str.endswith()
?
>>> "xyz.0.html".endswith(".0.html")
True
Upvotes: 5
Reputation: 251608
The error is just what it says. When you call name.index('0.html')
on the name "xyz.1.html"
, the string is not found. index
raises an error in this case. If you don't want this, you can use the find
method instead (which returns -1 if the substring is not found), or you can catch the exception.
Upvotes: 2
Reputation: 310297
you probably want
if '.0.html' in name:
Or,
if name.endswith('.0.html'):
Your version raises an error if the substring isn't in the string (and it will evaluate to False
if the substring is at the start of the string) since the index
method returns the index in the string where the substring was found (or raises an exception if the substring wasn't found).
Upvotes: 2
Reputation: 114108
try
if ".0.html" in name:
print name
or
if name.endswith(".0.html"):
print name
Upvotes: 2