views:

439

answers:

6

Hi all,

Im trying to rename some files in a directory using python. I've looked around the forums here, and because i'm a noob, I cant adapt what I need from what is out there.

Say I have a file called CHEESE_CHEESE_TYPE.*** and want to remove "Cheese_" so my resulting filename would be "CHEESE_TYPE"

Im trying to use the os.path.split but it's not working properly.

I have also considered using string manipulations, but have not been successful with that either.

Any help would be greatly appreciated. Thanks.

A: 

Here's a script based on your newest comment.

#!/usr/bin/env python
from os import rename, listdir

badprefix = "cheese_"
fnames = listdir('.')

for fname in fnames:
    if fname.startswith(badprefix*2):
        rename(fname, fname.replace(badprefix, '', 1))
bukzor
A: 

It seems that your problem is more in determining the new file name rather than the rename itself (for which you could use the os.rename method).

It is not clear from your question what the pattern is that you want to be renaming. There is nothing wrong with string manipulation. A regular expression may be what you need here.

Uri
+2  A: 

Do you want something like this?

$ ls
cheese_cheese_type.bar  cheese_cheese_type.foo
$ python
>>> import os
>>> for filename in os.listdir("."):
...  if filename.startswith("cheese_"):
...    os.rename(filename, filename[7:])
... 
>>> 
$ ls
cheese_type.bar  cheese_type.foo
Messa
Im getting an error from windows saying it cant find the file, and it's not doing anything...any tips?
Jeff
A: 

What about this :

import re
p = re.compile(r'_')
p.split(filename, 1) #where filename is CHEESE_CHEESE_TYPE.***
Bandan
A: 

Try this:

import os
import shutil

for file in os.listdir(dirpath):
    newfile = dirpath + "/" + file.split("_",1)[1]
    shutil.move(dirpath"/"+file,newfile)

I'm assuming you don't want to remove the file extension, but you can just do the same split with periods.

krs1
overriding the builtin 'file' is generally bad practice.
bukzor
A: 

Assuming you are already in the directory, and that the "first 8 characters" from your comment hold true always. (Although "CHEESE_" is 7 characters... ? If so, change the 8 below to 7)

from glob import glob
from os import rename
for fname in glob('*.prj'):
    rename(fname, fname[8:])
darelf