I am using python to rename files which exist as binary files but in actual are images. So I need to rename them into .jpg format. I am using os.rename() but getting the error:
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. Basically, the code as-is will only work when executed in the same directory as the one called by 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.
Related
I was trying to iterate over the files in a directory like this:
import os
path = r'E:/somedir'
for filename in os.listdir(path):
f = open(filename, 'r')
... # process the file
But Python was throwing FileNotFoundError even though the file exists:
Traceback (most recent call last):
File "E:/ADMTM/TestT.py", line 6, in <module>
f = open(filename, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'foo.txt'
So what is wrong here?
It is because os.listdir does not return the full path to the file, only the filename part; that is 'foo.txt', when open would want 'E:/somedir/foo.txt' because the file does not exist in the current directory.
Use os.path.join to prepend the directory to your filename:
path = r'E:/somedir'
for filename in os.listdir(path):
with open(os.path.join(path, filename)) as f:
... # process the file
(Also, you are not closing the file; the with block will take care of it automatically).
os.listdir(directory) returns a list of file names in directory. So unless directory is your current working directory, you need to join those file names with the actual directory to get a proper absolute path:
for filename in os.listdir(path):
filepath = os.path.join(path, filename)
f = open(filepath,'r')
raw = f.read()
# ...
Here's an alternative solution using pathlib.Path.iterdir, which yields the full paths instead, removing the need to join paths:
from pathlib import Path
path = Path(r'E:/somedir')
for filename in path.iterdir():
with filename.open() as f:
... # process the file
I was trying to iterate over the files in a directory like this:
import os
path = r'E:/somedir'
for filename in os.listdir(path):
f = open(filename, 'r')
... # process the file
But Python was throwing FileNotFoundError even though the file exists:
Traceback (most recent call last):
File "E:/ADMTM/TestT.py", line 6, in <module>
f = open(filename, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'foo.txt'
So what is wrong here?
It is because os.listdir does not return the full path to the file, only the filename part; that is 'foo.txt', when open would want 'E:/somedir/foo.txt' because the file does not exist in the current directory.
Use os.path.join to prepend the directory to your filename:
path = r'E:/somedir'
for filename in os.listdir(path):
with open(os.path.join(path, filename)) as f:
... # process the file
(Also, you are not closing the file; the with block will take care of it automatically).
os.listdir(directory) returns a list of file names in directory. So unless directory is your current working directory, you need to join those file names with the actual directory to get a proper absolute path:
for filename in os.listdir(path):
filepath = os.path.join(path, filename)
f = open(filepath,'r')
raw = f.read()
# ...
Here's an alternative solution using pathlib.Path.iterdir, which yields the full paths instead, removing the need to join paths:
from pathlib import Path
path = Path(r'E:/somedir')
for filename in path.iterdir():
with filename.open() as f:
... # process the file
I'm trying to rename a number of files stored within subdirectories by removing the last four characters in their basename. I normally use glob.glob() to locate and rename files in one directory using:
import glob, os
for file in glob.glob("C:/Users/username/Desktop/Original data/" + "*.*"):
pieces = list(os.path.splitext(file))
pieces[0] = pieces[0][:-4]
newFile = "".join(pieces)
os.rename(file,newFile)
But now I want to repeat the above in all subdirectories. I tried using os.walk():
import os
for subdir, dirs, files in os.walk("C:/Users/username/Desktop/Original data/"):
for file in files:
pieces = list(os.path.splitext(file))
pieces[0] = pieces[0][:-4]
newFile = "".join(pieces)
# print "Original filename: " + file, " || New filename: " + newFile
os.rename(file,newFile)
The print statement correctly prints the original and the new filenames that I am looking for but os.rename(file,newFile) returns the following error:
Traceback (most recent call last):
File "<input>", line 7, in <module>
WindowsError: [Error 2] The system cannot find the file specified
How could I resolve this?
You have to pass the full path of the file to os.rename. First item of the tuple returned by os.walk is the current path so just use os.path.join to combine it with file name:
import os
for path, dirs, files in os.walk("./data"):
for file in files:
pieces = list(os.path.splitext(file))
pieces[0] = pieces[0][:-4]
newFile = "".join(pieces)
os.rename(os.path.join(path, file), os.path.join(path, newFile))
I am trying the script below to rename all files in a folder.It is working fine,But when i am trying to run it outside the folder.It shows error.
import os
path=os.getcwd()
path=os.path.join(path,'it')
filenames = os.listdir(path)
i=0
for filename in filenames:
os.rename(filename, "%d.jpg"%i)
i=i+1
'it' is the name of the folder in which files lie.
Error:FileNotFoundError: [Errno 2] No such file or directory: '0.jpg' -> '0.jpg'
Print is showing names of files
When you do os.listdir(path) you get the filenames of files in the folder, but not the complete paths to those files. When you call os.rename you need the path to the file rather than just the filename.
You can join the filename to its parent folder's path using os.path.join.
E.g. os.path.join(path, file).
Something like this might work:
for filename in filenames:
old = os.path.join(path, filename)
new = os.path.join(path, "%d.jpg"%i)
os.rename(old, new)
i=i+1
You need to mention complete or relative path to file.
In this case, it should be
path + '/' + filename
or more generally,
newpath = os.path.join(path, filename)
I'm trying to rename all the pictures in a directory. I need to add a couple of pre-pending zero's to the filename. I'm new to Python and I have written the following script.
import os
path = "c:\\tmp"
dirList = os.listdir(path)
for fname in dirList:
fileName = os.path.splitext(fname)[0]
fileName = "00" + fname
os.rename(fname, fileName)
#print(fileName)
The commented print line was just to verify I was on the right track. When I run this I get the following error and I am at a loss how to resolve it.
Traceback (most recent call last): File
"C:\Python32\Code\add_zeros_to_std_imgs.py", line 15, in
os.rename(fname, fileName) WindowsError: [Error 2] The system cannot find the file specified
Any help is greatly appreciated. Thnx.
You should pass the absolute path to os.rename. Right now your only passing the filename itself. It isn't looking in the correct place. Use os.path.join.
Try this:
import os
path = "c:\\tmp"
dirList = os.listdir(path)
for fname in dirList:
fileName = os.path.splitext(fname)[0]
fileName = "00" + fname
os.rename(os.path.join(path, fname), os.path.join(path, fileName))
#print(fileName)