Renaming files in folder by it's date python - python

I want to rename photos in folder by it's date. This is my python script.
import os
from datetime import datetime
folder_name = 'D:/Users/user/Desktop/Xiomi/100ANDRO/'
dir_list = [os.path.join(folder_name, x) for x in os.listdir(folder_name)]
for file in dir_list:
filename, file_extension = os.path.splitext(file)
date = datetime.fromtimestamp(os.path.getctime(file)).strftime('%Y_%m_%d_%H_%M_%S')
os.rename(os.path.basename(file), date + file_extension)
print(dir_list)
But I have an error:
$ python script.py
Traceback (most recent call last):
File "script.py", line 10, in <module>
os.rename(os.path.basename(file), date + file_extension)
FileNotFoundError: [WinError 2] ▒▒ ▒▒▒▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒▒▒▒▒▒ ▒▒▒▒:
'DSC_0003.JPG' -> '2018_07_08_12_28_21.JPG'
The file is definitely in folder. Can you help me with it?

Why are you taking the base name from the target when the absolute path would be okay ?
os.rename works on files that exist. It works if you pass absolute paths provided that the files are located on the same drive. I'd do:
os.rename(file, os.path.join(folder_name,date + file_extension))
basically remove the basename, and add the folder name for the destination. Since the directory is the same for both, that'll work. And it's much cleaner than a dirty os.chdir(folder_name)

Looks to me like you need to give os.rename() the absolute path to the file
os.rename(file, os.path.join(folder_name, date + file_extension))

Related

Error while renaming files using os.rename()

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.

python file renaming using os module

This is the script
import os
x = os.listdir("/media/virus/Data/Songs/Taylor swift/Taylor Swift - 1989 (Deluxe Version)")
for i in x:
print i
os.rename(i,i[20:])
the error was shown as follows
virus#ShashwatVirus ~ $ python plsdelete.py
01 - Taylor Swift - Welcome To New York.mp3
Traceback (most recent call last):
File "plsdelete.py", line 5, in <module>
os.rename(i,i[20:])
OSError: [Errno 2] No such file or directory
The os module is listing the files correctly
But the problem arises when I try to rename
I also checked in /usr/lib/python 2.7
listdir returns the filenames inside the given folder, but not their complete paths. os.rename doesn't know that you think you're looking at files inside that particular folder. You're just giving it filenames with no context.
You can construct the paths to those filenames using os.path.join to join the folder path to the filename.
folder = "/media/virus/Data/Songs/Taylor swift/Taylor Swift - 1989 (Deluxe Version)"
filenames = os.listdir(folder)
for filename in filenames:
oldpath = os.path.join(folder, filename)
newpath = os.path.join(folder, filename[20:])
os.rename(oldpath, newpath)
You need to add the path to the filenames passed to rename:
import os
my_dir = "/media/virus/Data/Songs/Taylor swift/Taylor Swift - 1989 (Deluxe Version)"
x = os.listdir(my_dir)
for i in x:
print i
os.rename(os.path.join(my_dir, i), os.path.join(my_dir, i[20:]))
I got it
I just changed the working directory by adding
os.chdir("/media/virus/Data/Songs/Taylor swift/Taylor Swift - 1989 (Deluxe Version)")

rename file in Python: WindowsError: [Error 2] The system cannot find the file specified

I am trying to rename a file in a folder and i keep getting the error that the file is not there....
import os
import time
from os.path import isfile, join
working_dir = ('C:/Users/XXXXX/Desktop')
only_file = [f for f in os.listdir(working_dir) if os.path.isfile(os.path.join(working_dir, f))]
print only_file
time_srt = time.strftime("%d_%m_%Y")
if 'EZShift_WeeklyPerDayScheduleReport_Export.xlsx' in only_file:
os.rename('EZShift_WeeklyPerDayScheduleReport_Export.xlsx', "EZShift_" + time_srt + ".xlsx")
C:\Python27\python.exe
C:/Users/xxxxxx/Desktop/Paython/Python3/pbx.py
['xxxxxx.jpg', 'xxxx.zip', 'xxxx.xlsx', 'xxx.pdf', 'xxx.MOV', 'xx.MOV', 'xxxxx_18_12_2016.xlsx', 'EZShift_WeeklyPerDayScheduleReport_Export.xlsx','Test_EZShift_WeeklyPerDayScheduleReport_Export.xlsx']
Traceback (most recent call last):
File "C:/Users/sabaja/Desktop/Paython/Python3/pbx.py", line 24, in
os.rename('EZShift_WeeklyPerDayScheduleReport_Export.xlsx', "EZShift_" + time_srt + ".xlsx")
WindowsError: [Error 2] The system cannot find the file specified
Process finished with exit code 1
your filenames from os.listdir are relative paths (os.listdir returns the filenames onla); they will be searched for in your current working directory which is os.getcwd() (that will not be changed just because you name a variable working_dir)
you need to os.path.join(working_dir, filename) to get absolute paths in order to access (and rename) your files.
you could do something like this:
import os.path
if 'EZShift_WeeklyPerDayScheduleReport_Export.xlsx' in only_file:
old_path = os.path.join(working_dir, "EZShift_WeeklyPerDayScheduleReport_Export.xlsx")
new_path = os.path.join(working_dir, "EZShift_" + time_srt + ".xlsx")
os.rename(old_path, new_path)

How to rename files using os.walk()?

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))

Renaming multiple files in a directory using Python

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.
You are not giving the whole path while renaming, do it like this:
import os
path = '/Users/myName/Desktop/directory'
files = os.listdir(path)
for index, file in enumerate(files):
os.rename(os.path.join(path, file), os.path.join(path, ''.join([str(index), '.jpg'])))
Edit: Thanks to tavo, The first solution would move the file to the current directory, fixed that.
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)
import os
from os import path
import shutil
Source_Path = 'E:\Binayak\deep_learning\Datasets\Class_2'
Destination = 'E:\Binayak\deep_learning\Datasets\Class_2_Dest'
#dst_folder = os.mkdir(Destination)
def main():
for count, filename in enumerate(os.listdir(Source_Path)):
dst = "Class_2_" + str(count) + ".jpg"
# rename all the files
os.rename(os.path.join(Source_Path, filename), os.path.join(Destination, dst))
# Driver Code
if __name__ == '__main__':
main()
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'))
Just playing with the accepted answer define the path variable and list:
path = "/Your/path/to/folder/"
files = os.listdir(path)
and then loop over that list:
for index, file in enumerate(files):
#print (file)
os.rename(path+file, path +'file_' + str(index)+ '.jpg')
or loop over same way with one line as python list comprehension :
[os.rename(path+file, path +'jog_' + str(index)+ '.jpg') for index, file in enumerate(files)]
I think the first is more readable, in the second the first part of the loop is just the second part of the list comprehension
If your files are renaming in random manner then you have to sort the files in the directory first. The given code first sort then rename the files.
import os
import re
path = 'target_folder_directory'
files = os.listdir(path)
files.sort(key=lambda var:[int(x) if x.isdigit() else x for x in re.findall(r'[^0-9]|[0-9]+', var)])
for i, file in enumerate(files):
os.rename(path + file, path + "{}".format(i)+".jpg")
I wrote a quick and flexible script for renaming files, if you want a working solution without reinventing the wheel.
It renames files in the current directory by passing replacement functions.
Each function specifies a change you want done to all the matching file names. The code will determine the changes that will be done, and displays the differences it would generate using colors, and asks for confirmation to perform the changes.
You can find the source code here, and place it in the folder of which you want to rename files https://gist.github.com/aljgom/81e8e4ca9584b481523271b8725448b8
It works in pycharm, I haven't tested it in other consoles
The interaction will look something like this, after defining a few replacement functions
when it's running the first one, it would show all the differences from the files matching in the directory, and you can confirm to make the replacements or no, like this
This works for me and by increasing the index by 1 we can number the dataset.
import os
path = '/Users/myName/Desktop/directory'
files = os.listdir(path)
index=1
for index, file in enumerate(files):
os.rename(os.path.join(path, file),os.path.join(path,''.join([str(index),'.jpg'])))
index = index+1
But if your current image name start with a number this will not work.

Categories

Resources