Python脚本,让它更短

标签 python

如何使这段代码更短?有些代码是相似的,我认为它们可以合并为一个:

    if not os.path.exists(".\image_1_01.bmp"):
        print('image_1_01.bmp not generated\n' 'for more info check the log file' )
        return 1
    else:
        shutil.move(".\image_1_01.bmp", output_directory)

    if not os.path.exists(".\image_1_01.raw"):
        print('image_1_01.raw not generated\n' 'for mor info check the log file' )
        return 1
    else:
        shutil.move(".\image_1_01.raw", output_directory)

    if not os.path.exists(".\image_1_01_hist.csv"):
        print('image_1_01_hist.csv not generated\n' 'for mor info check the log file' )
        return 1
    else:
        shutil.move(".\image_1_01_hist.csv", output_directory)

    if not os.path.exists(".\image_1_02.bmp"):
        print('image_1_02.bmp not generated\n' 'for more info check the log file' )
        return 1
    else:
        shutil.move(".\image_1_02.bmp", output_directory)

    if not os.path.exists(".\image_1_02.raw"):
        print('image_1_02.raw not generated\n' 'for mor info check the log file' )
        return 1
    else:
        shutil.move(".\image_1_02.raw", output_directory)

    if not os.path.exists(".\image_1_02_hist.csv"):
        print('image_1_02_hist.csv not generated\n' 'for mor info check the log file' )
        return 1
    else:
        shutil.move(".\image_1_02_hist.csv", output_directory)

    if not os.path.exists(".\scan_stats.csv"):
        print('scan_stats.csv not generated\n' 'for mor info check the log file' )
        return 1
    else:
        shutil.move(".\scan_stats.csv", output_directory)`

最佳答案

images = [".\image_1_01.raw",".\image_1_01_hist.csv",".\image_1_02.bmp",".\image_1_02.raw",".\image_1_02_hist.csv",".\scan_stats.csv"]

for image in images:
    if not os.path.exists(image):
        print('{} not generated\n' 'for mor info check the log file'.format(image) )
        return 1
    else:
        shutil.move(image, output_directory)

关于Python脚本,让它更短,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60611733/

相关文章:

python - 导入错误: No module named jabber:python

python - 如何将格式化数字转换为常规数字(不带逗号或小数)

python - 需要帮助从 python 项目中的 pygtk GUI 实时捕获 STDOUT

python - Postgres : Retrieve records Sequentially at 5 seconds interval

python - 如何为不同Python进程之间的不同神经网络设置共享权重?

python - 如何跳过文档字符串中包含某些文本的测试?

python - Django 中的 SlugField 和覆盖保存

python - python中的reversed函数是如何实现的?

python - 模拟通过实例使用的类方法

python - 用于标记组中最大行的列