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

stacks=glob.glob('*.tif')

for stack in stacks:
	command="proc2d %s %s " %(stack,'mrc'+stack)
	os.system(command)
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!!
-Powerhouse

Recommended Answers

All 2 Replies

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

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

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'
'test.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.

HTH

Thank you very much. The os.path.splitext is exactly what i needed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.