Renaming multiple files in a directory using Pytho

2019-01-13 22:06发布

I'm trying to rename multiple files in a directory using this Python script:

import os
path = '/Users/myName/Desktop/directory'
files = os.listdir(path)
i = 1

for file in files:
    os.rename(file, str(i)+'.jpg')
    i = i+1

When I run this script, I get the following error:

Traceback (most recent call last):
  File "rename.py", line 7, in <module>
    os.rename(file, str(i)+'.jpg')
OSError: [Errno 2] No such file or directory

Why is that? How can I solve this issue?

Thanks.

4条回答
老娘就宠你
2楼-- · 2019-01-13 22:48

You can copy this script and place it in the folder of which you want to rename files. https://gist.github.com/aljgom/81e8e4ca9584b481523271b8725448b8

It renames files in current directory by passing it functions. First determines the changes that will be made and displays the differences using colors, and asks for confirmation to perform the changes. Works on pycharm, haven't tested it in different consoles

查看更多
SAY GOODBYE
3楼-- · 2019-01-13 22:50

You have to make this path as a current working directory first. simple enough. rest of the code has no errors.

to make it current working directory:

os.chdir(path)
查看更多
别忘想泡老子
4楼-- · 2019-01-13 22:57

As per @daniel's comment, os.listdir() returns just the filenames and not the full path of the file. Use os.path.join(path, file) to get the full path and rename that.

import os
path = 'C:\\Users\\Admin\\Desktop\\Jayesh'
files = os.listdir(path)
for file in files:
   os.rename(os.path.join(path, file), os.path.join(path, 'xyz_' + file + '.csv'))
查看更多
Animai°情兽
5楼-- · 2019-01-13 23:00

You are not giving the whole path while renaming, do it like this:

import os
path = '/Users/myName/Desktop/directory'
files = os.listdir(path)
i = 1

for file in files:
    os.rename(os.path.join(path, file), os.path.join(path, str(i)+'.jpg'))
    i = i+1

Edit: Thanks to tavo, The first solution would move the file to the current directory, fixed that.

查看更多
登录 后发表回答