I am writing some Python code to rename some files. In doing so, I have ran across a peculiar error. When I try to print anything after my join, nothing will print. Not even print 'test'
.
What could be causing this? Here is the code :
... #finding all images in a .html
for t in soup.find_all('img'): # Note: soup exists outside of with
try:
old_src = t['src'] # Access src attribute
image = os.path.split(old_src)[1] # Get file name
#print 'image => ' + image
relpath = os.path.relpath(root, do) # Get relative path from do to root
folders = relpath.strip('\\').split('\\') # Remove outer slashes, split on folder separator
#BELOW LINE CAUSES PROBLEM
new_src = '_'.join(folders.append(str(image))) # Join folders and image by underscore
print t['src'] #prints nothing
print 'test' #prints nothing
t['src'] = new_src # Modify src attribute
except: # Do nothing if tag does not have src attribute
pass
It confuses me that nothing prints below this line, as it clearly reaches the end of execution...it will not do anything after this line though as far as I can see. Execution stops completely.
Can anyone see any issue here?
Thanks.
folders.append(str(image))
returns nothing ( None
), so the program would raise an exception and skip your print
statements.
You can solve it simply by replacing your new_src = '_'.join(folders.append(str(image)))
with two following lines:
folders.append(str(image))
new_src = '_'.join(folders)
If you catch exception by except Exception as e:
and print e
, you will see the TypeError error message, because it's same as doing '_'.join(None)
by executing '_'.join(folders.append(str(image)))
假设folders
是一个正常的list
, folders.append
返回None
,但str.join
预计可迭代作为它的参数,所以它提出了一个TypeError
......然后将其捕获并通过您的忽视except: pass
,之后继续执行下下一个t in soup.find_all('img')
,因此永远不会到达print
位置。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.