繁体   English   中英

如何向python添加if和else语句?

[英]How do I add an if and else statement to python?

我目前正在学习 python 并且我正在尝试添加 if/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('-', '@'))

我想要的是,如果一个新文件被添加到目录中,那么它也会改变它。

但我认为因为没有 if/else 语句我得到一个错误:

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

所以,我想知道我是否可以添加类似的东西;

如果设置了 new_name,则跳过并继续循环。

谢谢您的帮助! :)

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

您可以通过在相关行周围使用try ... except ...解决此问题,如果它不适合该格式,则continue循环。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM