Trying renaming all files in a folder - python

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)

Related

How to only get files without extensions?

My problem is to get ONLY files without extensions.
I mean - I have a dictionary and there are some files without extensions and some files with extensions (.xml, .csv, etc)
I want that my code would only read files without extensions.
Now, it's reading every file in the dictionary "Dir".
path = 'C:/Users/STJ2TW/Desktop/Dir/'
for filename in os.listdir(path):
fullname = os.path.join(path, filename)
Thanks in advance!
You can split the filename using the splittext function and check for the ones which are not a directory and do not have an extension value (ext).
import os
path = os.getcwd()
for filename in os.listdir(path):
if not os.path.isdir(filename):
(name, ext) = os.path.splitext(filename)
if not ext:
# Your code here
If there are no dots in your files, you can do :
path = 'C:/Users/STJ2TW/Desktop/Dir/'
for filename in os.listdir(path):
if '.' not in filename:
fullname = os.path.join(path, filename)

i have an exported file that comes out with spaces, and i want to change that file to have hyphens

My current code is:
import os
path = os.getcwd()
filenames = os.listdir("C:/Users/Larso/Desktop/ClearEstimatesEstimate/")
filename = ('Leap Price Guide Export.xlsx')
for filename in filenames:
os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(' ', '-')))
for filename in filenames:
os.rename(filename, filename.replace(" ", "-"))
but i get error
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\Users\\larso\\Desktop\\ClearEstimatesEstimate\\AutomateExcelfileintoaspecficExcelfileformat\\AutomateExcelfileintoaspecficExcelfileformat' -> 'C:\\Users\\larso\\Desktop\\ClearEstimatesEstimate\\AutomateExcelfileintoaspecficExcelfileformat\\AutomateExcelfileintoaspecficExcelfileformat'
any thoughts how to automate that
Just a wild guess:
Has your path variable
path = os.getcwd()
the same path as your filenames path
filenames = os.listdir("C:/Users/Larso/Desktop/ClearEstimatesEstimate/")
Because you combine the path from the path variable with the filename from an filenames variable.
os.path.join(path, filename)
Please print both path values and compare them for differences. Or better use your path variable in your filenames variable:
filenames = os.listdir(path)
os.getcwd() is going to give you the path from which you're running the script.
os.listdir(path) is going to give you the list of filenames in the directory at path.
So the absolute path of the file in your working directory will be:
os.getcwd() + '/' + filename
Try this, with your script in the same directory as your files you want to rename.
import os
path = os.getcwd()
filenames = os.listdir(path)
for filename in filenames:
current_filename = path + '/' + filename
os.rename(current_filename, current_filename.replace('_', ' '))

How do I add extensions to files using python in multiple subdirectories

I need to add a .jpg extension to around 300K pictures. They are all in 12 sub-directories and four more subdirectories in each of those 12.
I tried following this post but didn't do a walk down to all subdirectories:
Adding extension to multiple files (Python3.5)
I also tried the following:
import os
path = 'C:\\Photos'
genmod = os.walk(path)
for path, pathnames, files in gen_obj:
for file in files:
head, tail = os.splitext(file)
if not tail:
src = os.path.join(path, pathnames, file)
dst = os.path.join(path, pathnames, file + '.jpg')
if not os.path.exists(dst): # check if the file doesn't exist
os.rename(src, dst)
The above runs but nothing happens.
The above runs but nothing happens.
I doubt that, there are 2 problems:
os.splitext should be os.path.splitext
os.path.join should not be given pathnames, so
os.path.join(path, pathnames, file)
should be
os.path.join(path, file)
and
os.path.join(path, pathnames, file + '.jpg')
should be
os.path.join(path, file + '.jpg')

Create a zip file from a directory, but not his fullpath

Im trying to create a zipfile with the content of a folder ( some dirs and files ) using the code belllow:
import zip,os
path = "c:\\tester\\folderToZip"
zip = zipfile.ZipFile("zippedFolder.zip", "w")
for root, dirs, files in os.walk(path):
for file in files:
zip.write(os.path.join(root, file))
zip.close()
But after the code runs, when i check the zip file, the zip file, instead having the content of the folder "folderToZip" ( ex: f1,f2,f2, a.txt,b.txt,c.txt ) it have the full path of the variable path.
So, the question is, how can i create a zipfile based on a folder content, but not his fullpath ?
write takes a second optional parameter arcname, which when specified will provide the name for the file stored. Use that to specify the name you want.
If you only want the filename:
import zip,os
path = "c:\\tester\\folderToZip"
zip = zipfile.ZipFile("zippedFolder.zip", "w")
for root, dirs, files in os.walk(path):
for file in files:
filename = os.path.join(root, file)
zip.write(filename, filename)
zip.close()

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

I am having a problem with this code. I am trying to rename all of the filenames within a folder so that they no longer have +'s in them! This has worked many times before but suddenly I get the error:
WindowsError: [Error 2] The system cannot find the file specified at line 26
Line 26 is the last line in the code.
Does anyone know why this is happening? I just promised someone I could do this in 5 minutes because I had a code! Shame it doesnt work!!
import os, glob, sys
folder = "C:\\Documents and Settings\\DuffA\\Bureaublad\\Johan\\10G304655_1"
for root, dirs, filenames in os.walk(folder):
for filename in filenames:
filename = os.path.join(root, filename)
old = "+"
new = "_"
for root, dirs, filenames in os.walk(folder):
for filename in filenames:
if old in filename:
print (filename)
os.rename(filename, filename.replace(old,new))
I suspect that you may be having issues with subdirectories.
If you have a directory with files "a", "b" and subdirectory "dir" with files "sub+1" and "sub+2", the call to os.walk() will yield the following values:
(('.',), ('dir',), ('a', 'b'))
(('dir',), (,), ('sub+1', 'sub+2'))
When you process the second tuple, you will call rename() with 'sub+1', 'sub_1' as the arguments, when what you want is 'dir\sub+1', 'dir\sub_1'.
To fix this, change the loop in your code to:
for root, dirs, filenames in os.walk(folder):
for filename in filenames:
filename = os.path.join(root, filename)
... process file here
which will concatenate the directory with the filename before you do anything with it.
Edit:
I think the above is the right answer, but not quite the right reason.
Assuming you have a file "File+1" in the directory, os.walk() will return
("C:/Documents and Settings/DuffA/Bureaublad/Johan/10G304655_1/", (,), ("File+1",))
Unless you are in the "10G304655_1" directory, when you call rename(), the file "File+1" will not be found in the current directory, as that is not the same as the directory os.walk() is looking in. By doing the call to os.path.join() yuo are telling rename to look in the right directory.
Edit 2
A example of the code required might be:
import os
# Use a raw string, to reduce errors with \ characters.
folder = r"C:\Documents and Settings\DuffA\Bureaublad\Johan\10G304655_1"
old = '+'
new = '_'
for root, dirs, filenames in os.walk(folder):
for filename in filenames:
if old in filename: # If a '+' in the filename
filename = os.path.join(root, filename) # Get the absolute path to the file.
print (filename)
os.rename(filename, filename.replace(old,new)) # Rename the file
You are using splitext to determine the source filename to rename:
filename_split = os.path.splitext(filename) # filename and extensionname (extension in [1])
filename_zero = filename_split[0]#
...
os.rename(filename_zero, filename_zero.replace('+','_'))
If you encounter a file with an extension, obviously, trying to rename the filename without the extension will lead to a "file not found" error.

Categories

Resources