如何执行python程序并自动将输出保存为不同的文件名

问题描述 投票:0回答:2

我有一个Python程序,该程序处理图像并将结果输出保存到文件中。我正在通过使用input()的控制台接收输入和输出文件名。但是我想用文件名将输出自动保存为“ input_file_name_out”之类的东西。注意输入文件名附带的字符串“ _out”

这将帮助我仅获取输入文件名的用户输入,从而为用户节省了很少的时间,因为他不需要每次都思考输出文件名应该是什么

示例代码段

if __name__ == "__main__":

    in_file = input()
    out_file = input()

    processed = process_image(in_file,out_file)

预期代码段

if __name__ == "__main__":

    in_file = input()
    # out_file = input() ------Not getting the file name from user thereby supplying only one argument to the below function

        processed = process_image(in_file)

# And within the function
def process_image(img):
    .
    .
    .
    out_file = img+"_out.jpg" ##### What should come here to achieve my requirement ########
    cv2.imwrite(out_file,processed_image)
python python-3.x
2个回答
0
投票

很简单!只需采用您要求的“ in_file”字符串,并将“ _out”连接到末尾并将其作为out_file传递即可。

cv2.imwrite(in_file+"_out",processed_image)

0
投票

您要做的就是

  • 采用从用户输入中获得的input_img.jpg
  • 用定界符input_img.jpg分割.,这将为您提供以下列表:['input_img', 'jpg']
  • 拾取第一个元素并添加_out.jpg后缀
def process_image(img):

    # you should split with delimiter ('.'), take the first 
    # element of the list and add "_out.jpg" suffix
    out_file = img.split('.')[0]+"_out.jpg" 
    cv2.imwrite(out_file,processed_image)


if __name__ == "__main__":

    in_file = input()
    processed = process_image(in_file)

© www.soinside.com 2019 - 2024. All rights reserved.