Hi, i'm new to python. I'm trying to input a stack of (prefix.tif) images, modify them to png files and output the new files as prefix.png. One code that i was told to use allows me to modify the input name by adding something to the beginning of the name. This code is:

#!/usr/bin/env python

import glob,os


for stack in stacks:
	command="proc2d %s %s " %(stack,'mrc'+stack)
print "image low passed"

**In this example, the proc2d command manipulates stack in stacks and "mrc" is added to stack.**
But what i'd like is to be able to change the suffix from .tif to .png. Any advice you give is greatly aprecaited!!

There's many ways to do this, here's two examples:

>>> stack = 'test.tif'
>>> new_name = stack.split('.')[0] + '.png'
>>> new_name

Simply split at the '.' and use the first part of the name, then add on .png
This is very straight forward, however it may produce unwanted behavior if you've got multiple '.' in your file names.

>>> import os
>>> os.path.splitext(stack)
('test', '.tif')
>>> os.path.splitext(stack)[0] + '.png'
>>> stack = 'test.bak.tif'
>>> os.path.splitext(stack)
('test.bak', '.tif')

Using splitext of the os.path module will give you both the base file name and the extension in a tuple. Now all you need to do is slice the basename out and add your new extension and BAM. New name.


This article has been dead for over six months. Start a new discussion instead.