Reputation: 35
I'm currently learning python and I'm trying to add if/else statements.
For example, I have this script that changes the file names within a directory to something else:
import os
#changes directory
os.chdir('/home/Documents/agreements')
for f in os.listdir('/home/rachellegarcia/Documents/agreements'):
f_name, f_ext = os.path.splitext(f)
f_patient, f_conf, f_agmt, f_email = f_name.split('_')
f_agmt_type, f_agmt_staff = f_agmt.split('-')
#sets the new name
new_name = '{}-{}{}'.format(f_agmt_staff, f_email, f_ext)
#renames the file
os.rename(f, new_name.replace('-', '@'))
What I would like is if a new file gets added to the directory, then it'll change it too.
But I think because don't have an if/else statement I get an error:
File "/home/Documents/python/renamefiles.py", line 8, in <module>
f_patient, f_conf, f_agmt, f_email = f_name.split('_')
ValueError: need more than 1 value to unpack
So, I wanted to know if I can add something like;
if the new_name is set, then skip and continue the loop.
Thanks for the help! :)
Upvotes: 0
Views: 56
Reputation: 23176
Your error is occurring because it is encountering a file that does not fit the format you expect ... of four parts separated by _
.
You could cope with this by using a try ... except ...
around the line in question and continue
-ing the loop if it does not fit that format.
for f in os.listdir('/home/rachellegarcia/Documents/agreements'):
f_name, f_ext = os.path.splitext(f)
try:
f_patient, f_conf, f_agmt, f_email = f_name.split('_')
except ValueError:
# ... it wasn't the format expected, skip it
continue
# ... it was the format expected
f_agmt_type, f_agmt_staff = f_agmt.split('-')
#sets the new name
new_name = '{}-{}{}'.format(f_agmt_staff, f_email, f_ext)
#renames the file
os.rename(f, new_name.replace('-', '@'))
In the long run it may be more robust to check each filename against a regular expression that describes the exact format you expect.
Upvotes: 1