I'm trying to write my first script.
I have been reading about python but I am stock.
I'm trying to write a script that will rename all the file names in a specific folder.
this is what I have so far:
import os
files = os.listdir('files_to_Change')
print (files)
Get all the file names from folder:
for i in files:
if i == ".DS_Store":
p = files.index(".DS_Store")
del files[p]
If mac invisible file exists delete from list (maybe a mistake here).
for i in files:
oldName = i
fileName, fileExtension = os.path.splitext(i)
print (oldName)
print (fileName)
os.rename(oldName,fileName)
This is where I am stock, I get this error:
Output:
FileNotFoundError: [Errno 2] No such file or directory: 'File.1'
On the above part I'm just removing the file extension, but that is only the beginning.
I'm also trying to substitute every point by a space and make the first letter of every word a capital.
Can anyone point me in the right direction?
Thanks so much
In your example, when you get a list of files in a files_to_Change directory, you get file names without the directory name:
>>> files = os.listdir('test_folder')
>>> print files[0]
.com.apple.timemachine.supported
So in order to get the full path to that file, from whereever you're in your directory tree, you should join the directory name (files_to_Change) with the file name:
import os
join = os.path.join
src = 'files_to_Change'
files = os.listdir( src )
for i in files:
old = i
new, ext = os.path.splitext ( old )
os.rename( join( src, old ), join( src, fileName ))
Related
I am trying to make a code that allows me to copy files from various subfolders to a new folder. The main problem and why it wasn't a straight forward thing to deal with since the beginning is that all the files start the same and end the same, just 1 letter changes in the file that I need.
I keep getting an error saying: "FileNotFoundError: [Errno 2] No such file or directory: '20210715 10.1_Plate_R_p00_0_B04f00d0.TIF'"
So far this is what I have:
import os,fnmatch, shutil
mainFolder = r"E:\Screening\202010715\20210715 Screening"
dst = r"C:\Users\**\Dropbox (**)\My PC\Desktop\Screening Data\20210715"
for subFolder in os.listdir(mainFolder):
sf = mainFolder+"/"+subFolder
id os.path.isdir(sf):
subset = fnmatch.filter(os.listdir(sf), "*_R_*")
for files in subset:
if '_R_' in files:
shutil.copy(files, dst)
PLEASE HELP!
The issue is that you aren't providing the full path to the file to shutil.copy, so it assumes the file exists in the folder you are running the script from. Another issue the code has, is that the subset variable gets replaced in each loop before you are able to copy the files you matched in the next loop.
import os, fnmatch, shutil
mainFolder = r"E:\Screening\202010715\20210715 Screening"
dst = r"C:\Users\**\Dropbox (**)\My PC\Desktop\Screening Data\20210715"
matches = [] # To store the matches
for subFolder in os.listdir(mainFolder):
sf = mainFolder + "/" + subFolder
if os.path.isdir(sf):
matches.extend([f'{sf}/{file}' for file in fnmatch.filter(os.listdir(sf), "*_R_*")]) # Append the full path to the file
for files in matches:
shutil.copy(files, dst)
Can't rename old files located in a folder in desktop. There are three files there item.pdf,item1.pdf and item2.pdf. What I wish to do now is rename those files to new_item.pdf,new_item1.pdf and new_item2.pdf.
I tried with the below script:
import os
filepath = "/Users/WCS/Desktop/all_files/"
for item in os.listdir(filepath):
os.rename(item,"new_name"+".pdf")
Executing the above script throws the following error. Whereas the folder address is accurate:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'item.pdf' -> 'new_name.pdf'
How can I rename these three files item.pdf,item1.pdf and item2.pdf to new_item.pdf,new_item1.pdf and new_item2.pdf from a folder?
Try this:
import os
import re
filepath = "/Users/WCS/Desktop/all_files/"
for item in os.listdir(filepath):
match = re.search(r'\d+$', item)
endnum = ""
if match:
endnum = match.group()
os.rename(os.path.join(filepath, item), os.path.join(filepath, "new_name{}.pdf".format(endnum)))
or, if you don't wanna use re
import os
filepath = "/Users/WCS/Desktop/all_files/"
for item in os.listdir(filepath):
new_name = item.replace('item', 'new_item')
os.rename(os.path.join(filepath, item), os.path.join(filepath, "new_name{}.pdf".format(new_name)))
You need to either specify the full path to your file in os.rename.
Something like:
for item in filepath:
os.rename(os.path.join(filepath, item), os.path.join(filepath, "new_item.pdf"))
Or change your current working directory to the directory where the files exist:
os.chdir("/your/file/path")
and then run your code.
See also https://docs.python.org/2/library/os.html#os.rename
I have a directory which contains different file names. The other directory I have is a directory of directories, such that each directory has the same name of the filename in the first directory.
What I want to do is that I would like to check if a file exists in the directory of directories through its name.
While working on this I had to make different for-loops and was a bit confusing. Is there a simpler way to do that in Python?
Well, here's what I did so far:
import os
directory_of_files_path = '/home/user/directory_of_files'
directory_of_directories_path = '/home/user/directory_of_directories'
i = 0
for root_pairs, dirs_pairs, files_pairs in os.walk(directory_of_files_path):
for root_aligned, dirs_aligned, files_aligned in os.walk(directory_of_directories_path):
for file in files_pairs:
for directory in dirs_aligned:
filename, file_extension = os.path.splitext(file)
if filename == directory:
i = i + 1
As you can see, in the above code I was able to return the number of files included in the directory of directories (based on name). But, couldn't figure out to check those that are not included in the directory of directories.
Thanks.
Don't know if I understood what you wanted to do but... here is my guess:
This is how I made the files and dirs
import os
dir_files = 'dir_files'
dir_dir = 'dir_dir'
i = 0
for rf, df, ff in os.walk(dir_files):
ff2 = ff
for rd, dd, fd in os.walk(dir_dir):
for dirs in dd:
if dirs + ".txt" in ff:
i += 1
ff2.remove(dirs + ".txt")
print("There are ", i, "dirs that matches with the files")
print("not found dir corresponding to {}".format(ff2))
Output
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.
I have multiple folders that look like folder.0 and folder.1.
Inside each folder there is one file ('junk') that I want to copy and rename to the .0 or .1 part of the folder name in which it currently resides.
Here is what I'm trying to do:
inDirec = '/foobar'
outDirec = '/complete/foobar'
for root, dirs,files in os.walk(inDirec):
for file in files:
if file =='junk'
d = os.path.split(root)[1]
filename, iterator = os.path.splitext(d) # folder no. captured
os.rename(file, iterator+file) # change name to include folder no.
fullpath = os.path.join(root,file)
shutil.copy(fullpath,outDirec)
This returns:
os.rename(file,iterator+file)
OSError: [Errno 2] No such file or directory
I'm not even sure I should be using os.rename. I just want to pull out files == 'junk' and copy them to one directory but they all have the exact same name. So I really just need to rename them so they can exist in the same directory. Any help?
Update
for root, dirs,files in os.walk(inDirec):
for file in files:
if file =='junk'
d = os.path.split(root)[1]
filename, iterator = os.path.splitext(d) # folder no. captured
it = iterator[-1] # iterator began with a '.'
shutil.copy(os.path.join(root,file),os.path.join(outDirec,it+file))
Your problem is that your program is using the working directory at launch for your rename operation. You need to provide full relative or absolute paths as arguments to os.rename().
Replace:
os.rename(file, iterator+file)
fullpath = os.path.join(root,file)
shutil.copy(fullpath,outDirec)
With (if you want to move):
os.rename(os.path.join(root, file), os.path.join(outDirec, iterator+file))
Or with (if you want to copy):
shutil.copy(os.path.join(root, file), os.path.join(outDirec, iterator+file))
NOTE: The destination directory should already exist or you will need code to create it.