[英]Error while renaming files using os.rename()
I am using python to rename files which exist as binary files but in actual are images. 我正在使用python重命名以二进制文件形式存在但实际上是图像的文件。 So I need to rename them into .jpg format.
所以我需要将它们重命名为.jpg格式。 I am using os.rename() but getting the error:
我正在使用os.rename()但出现错误:
Traceback (most recent call last):
File "addext.py", line 8, in <module>
os.rename(filename, filename + '.jpg')
OSError: [Errno 2] No such file or directory
Here's my code. 这是我的代码。
import os
for filename in os.listdir('/home/gpuuser/Aditya_Nigam/lum2/'):
# print(filename + '.jpg')
# k = str(filename)
# print k
# k = filename + '.jpg'
os.rename(filename, filename + '.jpg')
print('Done')
os.listdir
only return a list of filenames without their absolute paths, and os.rename
will attempt to lookup a filename from the current directory unless given an absolute path. os.listdir
仅返回没有绝对路径的文件名列表,并且os.rename
将尝试从当前目录中查找文件名,除非给出了绝对路径。 Basically, the code as-is will only work when executed in the same directory as the one called by os.listdir
. 基本上,仅当在与
os.listdir
调用的目录相同的目录中执行代码时,原样的代码才能工作。
Consider doing the following: 考虑执行以下操作:
import os
from os.path import join
path = '/home/gpuuser/Aditya_Nigam/lum2/'
for filename in os.listdir(path):
os.rename(join(path, filename), join(path, filename) + '.jpg')
The os.path.join
method will safely join the path with the filenames together in a platform agnostic manner. os.path.join
方法将以与平台无关的方式将路径和文件名安全地连接在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.