简体   繁体   English

无法重命名目录中的所有文件

[英]Can't rename all files in a directory

I need to rename all files to 'DSC0 + num' , so the final name of a file should be (for example) 'DSC02015' 我需要将所有文件重命名为'DSC0 + num' ,因此文件的最终名称应为(例如) '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: 所以把它放在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. 如果您的python脚本位于另一个目录中,那将是工作目录,并且由于您只有文件名而不是绝对文件路径,因此无法在该工作目录中解析这些文件。 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. 问题是您向rename函数提供了相对路径,但您可能从不同的位置执行代码。 You can either change the current folder with os.chdir as the previous answer. 您可以使用os.chdir更改当前文件夹作为上一个答案。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM