首页 > 解决方案 > How do I add an if and else statement to python?

问题描述

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! :)

标签: python

解决方案


您的错误正在发生,因为它遇到的文件不符合您期望的格式......由 . 分隔的四个部分组成_

try ... except ...您可以通过在有问题的行周围使用 a来解决这个问题,continue如果它不符合该格式,则 -ing 循环。

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('-', '@'))

从长远来看,根据描述您期望的确切格式的正则表达式检查每个文件名可能会更可靠。


推荐阅读