2

I have looked at the code here and it doesn't look that hard.

Can't resolve WindowsError: [Error 2] The system cannot find the file specified

However, it doesn't work in my case. I quite new to Python here. I am renaming the folders instead of the files. Then each of these folders have some files that need to be renamed too.

Here is what I have so far in renaming the folders in a directory:

import os
from os import rename, listdir

path = r"E:\myFolder"
dirList = os.listdir(path)
print str(dirList)

for name in dirList:
    nameOrig = (name[0:(len(name)-12)])
    nameRename = nameOrig + "City"
    os.rename((os.path.join(path, nameOrig), os.path.join(path, nameRename))

Thanks very much

Community
  • 1
  • 1
Jook
  • 21
  • 1
  • 2
  • 1
    If the error message occurred without the print statement from line 6 I would suspect that you had no folder named E:\myFolder. Did you? – Jim Jan 23 '14 at 00:25
  • Alternatively your rename is not using the actual name of the file so I would expect it to fail. Note that for a file named foo456789012345 the rename call would attempt to rename E:\myFolder\foo to E:\myFolder\fooCity On the last line shouldn't you use name and not nameOrig? – Jim Jan 23 '14 at 00:31

2 Answers2

0

1) I'm not sure what the (name[0:(len(name)-12)]) is doing... name should be the name of the directory itself to rename, which I would infer is nameOrig

2) os.rename((os.path.join(path, nameOrig), os.path.join(path, nameRename)) has unbalanced parenthesis. Typo?

This works for renaming things in my directory if I remove one open paren from the beginning of the rename function call. and set nameOrig = name

*Note, I am using a Linux version of Python, which may or may not treat the results from the dir list differently

Ryan J
  • 8,275
  • 3
  • 25
  • 28
0

Thank you very much for your help. Jim was right, I need to use 'name' instead of 'nameOrig' in the last line. And thanks to Ryan J who caught the extra paren

The line that says

nameOrig = (name[0:(len(name)-12)])

is suppose to take out the last 12 characters out and replace it with a new name. In this case it is 'City'

So I had the folder names called

031_Indianapolis 032_Indianapolis 033_Indianapolis 034_Indianapolis ...and so on...

and I changed to 031_City 032_City 033_City 034_City ....

Here is the final code:

import os from os import rename, listdir

path = r"E:\myFolder" dirList = os.listdir(path) print str(dirList)

for name in dirList: nameOrig = (name[0:(len(name)-12)]) nameRename = nameOrig + "City" os.rename(os.path.join(path, name), os.path.join(path, nameRename))

print "/n all processed"

Jook
  • 21
  • 1
  • 2