python file renaming using os module - python

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

Related

Error while renaming files with os.rename() in Python

import os
for filename in os.listdir("C:/Users/Awesome/Music"):
if filename.endswith("lyrics.mp3"):
os.rename(filename,filename[0 : len(filename)-11]+".mp3")
The code above returns the error
File "c:/python/lyrics-pop.py", line 6, in <module>
os.rename(filename,filename[0 : len(filename)-11]+".mp3")
FileNotFoundError: [WinError 2] The system cannot find the file specified: '2 Chainz - Bigger Than You (feat Drake Quavo) lyrics.mp3' -> '2 Chainz - Bigger Than You (feat Drake Quavo).mp3'
"""
I have made sure that no other program is accessing the .mp3 files and removed the readonly attribute. What could be causing this?
Probably, the issue is that you are passing relative path to os.rename, add dir to file path, like this:
import os
dir = "C:/Users/Awesome/Music"
for filename in os.listdir(dir):
if filename.endswith("lyrics.mp3"):
os.rename(os.path.join(dir,filename),os.path.join(dir,filename[0 : len(filename)-11])+".mp3")
This is because python can not find the file from where this program is running, since full path is not given.
You can do it as follows:
import os
filedir = "C:/Users/Awesome/Music"
for filename in os.listdir(filedir):
if filename.endswith("lyrics.mp3"):
filepath = os.path.join(filedir, filename)
new_file = os.path.join(filedir, filename[0 : len(filename)-11]+".mp3")
os.rename(filepath, new_file)
As suggested in the comments, the problem seems to be the relative path of the files.
You can use glob, which will give you the full path, i.e.:
from glob import glob
from os import rename
for f in glob("C:/Users/Awesome/Music/*lyrics.mp3"):
rename(f, f[0 : len(f)-11]+".mp3")

Renaming files in folder by it's date 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))

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.

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.

Python:writing files in a folder to zipfile and compressing it

I am trying to zip and compress all the files in a folder using python. The eventual goal is to make this occur in windows task scheduler.
import os
import zipfile
src = ("C:\Users\Blah\Desktop\Test")
os.chdir=(src)
path = (r"C:\Users\Blah\Desktop\Test")
dirs = os.listdir(path)
zf = zipfile.ZipFile("myzipfile.zip", "w", zipfile.ZIP_DEFLATED,allowZip64=True)
for file in dirs:
zf.write(file)
Now when I run this script I get the error:
WindowsError: [Error 2] The system cannot find the file specified: 'test1.bak'
I know it's there since it found the name of the file it can't find.
I'm wondering why it is not zipping and why this error is occurring.
There are large .bak files so they could run above 4GB, which is why I'm allowing 64 bit.
Edit: Success thanks everyone for answering my question here is my final code that works, hope this helps my future googlers:
import os
import zipfile
path = (r"C:\Users\vikram.medhekar\Desktop\Launch")
os.chdir(path)
dirs = os.listdir(path)
zf = zipfile.ZipFile("myzipfile.zip", "w", zipfile.ZIP_DEFLATED,allowZip64=True)
for file in dirs:
zf.write(os.path.join(file))
zf.close()
os.listdir(path) returns names relative to path - you need to use zf.write(os.path.join(path, file)) to tell it the full location of the file.
As I said twice in my comments:
Python is not looking for the file in the folder that it's in, but in the current working directory. Instead of
zf.write(file)
you'll need to
zf.write(path + os.pathsep + file)

Categories

Resources