문제

I need to rename all files to 'DSC0 + num', so the final name of a file should be (for example) 'DSC02015'

Attempted code:

import os

path = "C:\\images"
num = 2000
i=0
files = os.listdir(path)
for x in files:
    old = files[i]
    new = 'DSC0%d' %(num)   
    os.rename (files[i],new)
    num +=1
    i +=1

I'm getting this error:

Traceback <most recent call last):
 File "rename.py", line 10, in <module>
   os.rename (files[i],new)
WindowsError: [Error 2] The system cannot find the file specified
도움이 되었습니까?

해결책

You have to change to the right directory first. So put this in front of the for-loop:

os.chdir(path)

If your python script is in another directory, that will be the working directory and since you only have filenames and not absolute file paths, the files can't be resolved in that working directory. Changing to it therefore solves your problem.

As a side note, your loop could be a bit simpler. This should do the same:

for x in files:
  new = 'DSC0%d' %(num)   
  os.rename (x, new)
  num +=1

다른 팁

The problem is that you provide to the rename function a relative path but you probably execute the code from a different location. You can either change the current folder with os.chdir as the previous answer. or, if you want to stay in the original folder, you can supply full path in this way:

you need to change the line:

os.rename(files[i],new)

to be:

os.rename(os.path.join(path,files[i]),os.path.join(path,new))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top