geoJshaun
geoJshaun

Reputation: 709

os.rename not working

I try to rename files. Do not want file begins with "__". Tried using code from post: Removing characters from filename in batch

When making list:

myDir = os.listdir(r"S:\Shared\Santa Rosa")
for x in myDir:
  ...

I get this output:

Tuesday
Wednesday
__1831.pdf
__1832.pdf
__1833.pdf
__1834.pdf
__1841.pdf
__1842.pdf
__1843.pdf
__1844.pdf
__1851.pdf
__1852.pdf
__1853.pdf
__1854.pdf
__1861.pdf
__1862.pdf

But when do this:

for x in myDir:
    os.rename(x, x.replace('__', ''))

I get error:

Traceback (most recent call last):
  File "<interactive input>", line 2, in <module>
WindowsError: [Error 2] The system cannot find the file specified

Upvotes: 2

Views: 2960

Answers (4)

tdelaney
tdelaney

Reputation: 77377

This is a job for glob. Use it to filter filenames. And since it returns a usable path, you don't need os.path.join.

>>> from glob import glob
>>> import os
>>> for fn in glob("tmp/__*.pdf"):
...     print(fn)
...     os.rename(fn, fn.replace("__", ""))
... 
tmp/__aaa.pdf
tmp/__bbb.pdf

Upvotes: 1

Joseph Sheedy
Joseph Sheedy

Reputation: 6736

You should give the full pathname to os.rename, e.g. something like

dirName = r"S:\Shared\Santa Rosa"
myDir = os.listdir(dirName)
for x in myDir:
    oldName = os.path.join(dirName, x)
    newName = os.path.join(dirName, x.replace('__', ''))
    os.rename(oldName, newName)

Upvotes: 2

merlin2011
merlin2011

Reputation: 75585

Use os.path.join to get the full path.

dirPath = r"S:\Shared\Santa Rosa"
myDir = os.listdir(dirPath)
for x in myDir:
   x = os.path.join(myDir, x)
   os.rename(x, x.replace('__', ''))

Upvotes: 0

Barmar
Barmar

Reputation: 781934

os.rename() needs the full path to the file:

os.rename(os.path.join(r"S:\Shared\Santa Rosa", x), os.path.join(r"S:\Shared\Santa Rosa", x.replace("__", ""))

Upvotes: 0

Related Questions