[Tutor] New to Python..Need help

Alan Gauld alan.gauld at btinternet.com
Thu Sep 4 21:16:04 CEST 2014


On 04/09/14 13:49, Felisha Lawrence wrote:

> 'swp.113006004000_KLWX_0.0.5_PPI_v2','swp.113006004000_KLWX_0.0.5_PPI_v3'.
> I need to remove the characters after the 'v' and replace with v20. All of
> the endings of the files are sequential _v2, _v3,_v4, _v5. I need all of
> these characters to be the same (i.e. v20).

How else will you differentiate them if the files are all the same? Do 
you need to add a sequence number or do you really want to concateate 
the files into one big file?

> I would like to know which
> modules are best to use, and how to use loops to alter them.

You can use os.listdir to get all the filenames in a single folder

You can use glob.glob to get a subset of the files
     (using * and ? as wildvards)

You can use os.walk to get all the files/folders from a directry tree


Once you have the list of files you can use a for loop to access each name.

You can the use

string.replace()  to make simple changes
re.sub() to replace regular expressions

Or you could use string slicing to replace certain characters
based on position, wjhich might work well for your case.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list