简体   繁体   English

python3中的os.rename function不起作用

[英]os.rename function in python3 does not work

I have two folders.我有两个文件夹。 folder A and folder B. They all have images I scraped off the internet.文件夹 A 和文件夹 B。它们都有我从互联网上刮下来的图像。 Each of them have files like image01, image02, download1, download2 and so on.他们每个人都有像 image01、image02、download1、download2 等文件。 I wanted to rename all the files in the folders sequentially.我想按顺序重命名文件夹中的所有文件。 For eg- Files in folder A would have files as a1, a2, a3, etc. And files in folder B would have files as b1, b2, b3, etc. Here's what I've done till now for A(Ill repeat the same for B):例如,文件夹 A 中的文件将具有 a1、a2、a3 等文件。文件夹 B 中的文件将具有 b1、b2、b3 等文件。这是我到目前为止为 A 所做的(我会重复B)相同:

import os #For performing os related functions

count = 0 #For counting file number

for i in os.listdir("/path/to/folder/a/"): #Open the folder
  ext = i.split(".")[1] #Get the extension of the file
  name = "a"+str(count)+ext #Store the name of the file in a variable
  os.rename(i, name) #Rename the file
  count+=1 #Increase the count for the next file

And it throws the following error:它会引发以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'download.jpeg' -> 'a0jpeg'

The said file does exist.所述文件确实存在。 But I delete it and then try again.但是我删除它然后再试一次。 It does the same with another file.它对另一个文件执行相同的操作。 I do the same thing.我做同样的事情。 This happens a few more times until I realize that it's picking random files and then putting them in the error.这种情况又发生了几次,直到我意识到它正在选择随机文件,然后将它们放入错误中。 What do I do now?现在我该怎么做?

It is looking for 'download.jpeg' in current directory, try this:它正在当前目录中寻找'download.jpeg' ,试试这个:

import os #For performing os related functions

count = 0 #For counting file number

for i in os.listdir("/path/to/folder/a/"): #Open the folder
  ext = i.split(".")[1] #Get the extension of the file
  name = "a"+str(count)+ext #Store the name of the file in a variable
  orig_name = os.path.join("/path/to/folder/a/", i)
  name = os.path.join("/path/to/folder/a/", name)
  os.rename(orig_name, name) #Rename the file
  count+=1 #Increase the count for the next file

the.split() method removes the symbol you splitted, so you should add a dot before the extension .split() 方法会删除您拆分的符号,因此您应该在扩展名之前添加一个点

also using the.rename method needs the starting path and the final path同样使用 .rename 方法需要起始路径和最终路径

to fix your problem解决你的问题

import os
count = 0
for i in os.listdir(r"PATH HERE"):
    ext = i.split(".")[1] #Get the extension of the file
    name = "a"+str(count)+'.'+ext #Store the name of the file in a variable
    os.rename(r'PATH HERE\\'+ i, r'PATH HERE\\'+ name) 
    count+=1 #Increase the count for the next file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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