I am trying to make a program that can capitalize any file name.
here is my code:
import os
file = os.walk("E:\Work\experiment\ex")
for root, dirs, files in file:
fil = files[1]
cap = fil.capitalize()
new_name = os.renames(fil, cap)
print(new_name)
But I am getting this error:
[WinError 2] The system cannot find the file specified: 'basic_problm_2.py' -> 'Basic_problm_2.py'
You are forgetting that fil is equal to the name of file. When you call os.renames, it looks for that file in the current directory and it doesn't find it, thus the error is raised. You have to send absolute path to the renames method:
import os
file = os.walk("E:\Work\experiment\ex")
for root, dirs, files in file:
fil = files[1]
cap = fil.capitalize()
new_name = os.renames(os.path.join(root, fil), os.path.join(root, cap))
print(new_name)
os.path.join simply joins the arguments it takes. root is the directory where the fil is, so os.path.join(root, fil) will give you the absolute path.
import os
path = "C:/foo/foo/test/"
for filename in os.listdir(path):
if os.path.isfile(os.path.join(path, filename)):
os.rename(
os.path.join(path, filename), os.path.join(path, filename.capitalize())
)
This should do the trick. I'll also recommend using forward slash / with directories as backslash \ can cause issues (Another option is you can use // instead).
Related
I have a lot of folders. in each folder, there is an image. I want to rename all of the images with the name of its folder.
For example:
Folder "1" has an image "273.jpg" I want to change it into the "1.jpg" and save it in another directory.
This is what I have done so far:
import os
import pathlib
root = "Q:/1_Projekte/2980/"
for path, subdirs, files in os.walk(root):
for name in files:
print (pathlib.PurePath(path, name))
os.rename(os.path.join(path, name), os.path.join(path, os.path.basename(path)))
print(os.path.basename(path))
The problem is that it works just for the first folder, then it jumps out with the error:
this file is already available...
the tree of folders and the images are like this:
Q:/1_Projekte/2980/1/43425.jpg
Q:/1_Projekte/2980/2/43465.jpg
Q:/1_Projekte/2980/3/43483.jpg
Q:/1_Projekte/2980/4/43499.jpg
So there is just one file in each directory!
Probably you have some hidden files in those directories. Check it out. If those files are not jpg, you can use following code:
for path, subdirs, files in os.walk(root):
for name in files:
extension = name.split(".")[-1].lower()
if extension != "jpg":
continue
os.rename(os.path.join(path, name), os.path.join(path, os.path.basename(path) + "." + extension))
print(os.path.basename(path))
This code extracts the extension of the file and checks if it is equal to the jpg. If file extension is not jpg, so continue statement will run and next file will check. If file type is jpg, script renames it. Also this code adds original file extension to the new name. Previous code didn't handle that.
I hope this helpe you.
Maybe this might help...
import os
root = "Q:/1_Projekte/2980/"
subdirs = [x for x in os.listdir(root) if os.path.isdir(x)]
for dir_name in subdirs:
dir_path = root + dir_name + '/'
files = os.listdir(dir_path)
print(dir_name)
print(files)
for i in files:
counter = 1
extension = i.split('.')[-1]
new_name = dir_name + '.' + extension
while True:
try:
os.rename(dir_path + i, dir_path + new_name)
break
except:
# If the file exists...
new_name = dir_name + '({})'.format(counter) + '.' + extension
counter += 1
This code ensures that even if a file with the existing name happens to exist, it will be suffixed with a number in brackets.
Im ney to python and therefore apologize for the triviality of my question:
I have the following file structure, where a .csv file with employee is saved on daily basis:
dir/2012-01-01/employee.csv.bz2
dir/2012-01-02/employee.csv.bz2
dir/2012-01-03/employee.csv.bz2
dir/2012-01-04/employee.csv.bz2
dir/2012-01-05/employee.csv.bz2
I would like to go through each file and rename it. Afterwards I would like to save the new files in one common directory dir/common. What I tried:
import sys
import os
path = 'dir/'
for folderName, subfolders, filenames in os.walk(path):
for filename in filenames:
infilename = os.path.join(path, filename)
newname = infilename.replace('.csv.bz2', '.csv')
output = os.rename(infilename, newname)
But I get the error:
output = os.rename(infilename, newname)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'dir/employee.csv.bz2' -> 'dir/employee.csv'
Not sure what Im doing wrong.
Use folderName instead of path in os.path.join(path, filename) because folderName has full path to subfolder.
infilename = os.path.join(folderName, filename)
If you want to save in one folder then use this folder in newname and rename() will move file to new place.
newname = os.path.join('dir', 'common', filename.replace('.csv.bz2', '.csv'))
BTW: But you have to create this folder first.
os.mkdir('dir/common')
or to create folder and all intermediate folders from path
os.makedirs('dir/common/many/sub/folders/to/create')
infilename = os.path.join(path, filename)
You are missing the subfolder, which is evident from the error message: 'dir/employee.csv.bz2'.
I am having a difficult time creating a python script that will rename file extensions in a folder and continue to do so in sub directories. Here is the script I have thus far; it can only rename files in the top directory:
#!/usr/bin/python
# Usage: python rename_file_extensions.py
import os
import sys
for filename in os.listdir ("C:\\Users\\username\\Desktop\\test\\"): # parse through file list in the folder "test"
if filename.find(".jpg") > 0: # if an .jpg is found
newfilename = filename.replace(".jpg","jpeg") # convert .jpg to jpeg
os.rename(filename, newfilename) # rename the file
import os
import sys
directory = os.path.dirname(os.path.realpath(sys.argv[0])) #get the directory of your script
for subdir, dirs, files in os.walk(directory):
for filename in files:
if filename.find('.jpg') > 0:
subdirectoryPath = os.path.relpath(subdir, directory) #get the path to your subdirectory
filePath = os.path.join(subdirectoryPath, filename) #get the path to your file
newFilePath = filePath.replace(".jpg",".jpeg") #create the new name
os.rename(filePath, newFilePath) #rename your file
I modified Jaron's answer with the path to the file and the complete example of renaming the file
I modified the answer of Hector Rodriguez Jr. a little bit because it would replace ANY occurance of ".jpg" in the path, e.g. /path/to/my.jpg.files/001.jpg would become /path/to/my.jpeg.files/001.jpeg, which is not what you wanted, right?
Although it is generally not a good idea to use dots "." in a folder name, it can happen...
import os
import sys
directory = os.path.dirname(os.path.realpath(sys.argv[0])) # directory of your script
for subdir, dirs, files in os.walk(directory):
for filename in files:
if filename.find('.jpg') > 0:
newFilename = filename.replace(".jpg", ".jpeg") # replace only in filename
subdirectoryPath = os.path.relpath(subdir, directory) # path to subdirectory
filePath = os.path.join(subdirectoryPath, filename) # path to file
newFilePath = os.path.join(subdirectoryPath, newFilename) # new path
os.rename(filePath, newFilePath) # rename
You can process the directory like this:
import os
def process_directory(root):
for item in os.listdir(root):
if os.path.isdir(item):
print("is directory", item)
process_directory(item)
else:
print(item)
#Do stuff
process_directory(os.getcwd())
Although, this isn't really necessary. Simply use os.walk which will iterate through all toplevel and further directories / files
Do it like this:
for subdir, dirs, files in os.walk(root):
for f in files:
if f.find('.jpg') > 0:
#The rest of your stuff
That should do exactly what you want.
I have let's say 5 directories, let's call them dir1, dir2, dir3, dir4, dir5.
These are all in the current directory. Each of them contains 1 files called title.mkv. I want to rename the files to the directory name they are in, ie the file title.mkv in dir1, I want to rename to dir1.mkv.
I also want to then move the file to another folder. What python tools do I need for this besides os and glob?
If you have the full filename and directory, to rename the files, you can use
import os
f_name = 'E:/temp/nuke.mkv'
# Removes '/' at the end of string
while f_name.endswith('/'):
f_name = f_name[:-1]
# Generates List Containing Directories and File Name
f_name_split = f_name.split('/')
f_path = ''
# Iterates Through f_name_split, adding directories to new_f_path
for i in range(len(f_name_split)-1):
f_path += f_name_split[i] + '/'
# Makes New Name Based On Folder Name
new_name = f_name_split[-2] + '.mkv'
# Gets The Old File Name
f_name = f_name_split[-1]
# Renames The File
os.rename(f_path + f_name, f_path + new_name)
To go through all of the directories, you could do it recursively, have the system output it to a file [windows: dir /s /b /a > file.txt], or use os.walk. To move a file, you can use os.rename(source, destination)
The following should work, although you will have problems if there is more than one file per source folder:
import os
source_folder = r"c:\my_source_folder"
target_folder = r"c:\target_folder"
for directory_path, dirs, files in os.walk(source_folder):
# Current directory name
directory = os.path.split(directory_path)[1]
# Ensure only MKV files are processed
files = [file for file in files if os.path.splitext(file)[1].lower() == '.mkv']
# Rename each file
for file in files:
source = os.path.join(directory_path, file)
target = os.path.join(target_folder, directory + ".mkv")
try:
os.rename(source, target)
except OSError:
print "Failed to rename: {} to {}".format(source, target)
It will search all sub folders from the source folder and use the current folder name for the target name.
The following function uses shutil.move, which moves across filesystem and has overwrite protection in case destination file exists. File name can be relative.
from os.path import basename, dirname, isfile, abspath, splitext
from shutil import move
def rename_to_dirname_and_move(name, dst, overwrite=False, verbose=False):
"""renames 'name' to its directory name, keeping its extension
intact and moves to 'dst' directory across filesystem
"""
if not isfile(name):
raise ValueError("{} is not a file or doesn't exist".format(name))
abs_name = abspath(name)
dir_name = basename(dirname(abs_name))
new_name = '{}{}'.format(dir_name, splitext(name)[1])
dst_name = os.path.join(dst, new_name)
if not overwrite and isfile(dst_name):
raise OSError('file {} exists'.format(dst_name))
try:
move(abs_name, dst_name)
except Exception as e:
print("Can't move {} to {}, error: {}".format(abs_name, dst_name,e))
else:
if verbose:
print('Moved {} to {}'.format(abs_name, dst_name))
There are many posts related with moving several files from one existing directory to another existing directory. Unfortunately, that has not worked for me yet, in Windows 8 and Python 2.7.
My best attempt seems to be with this code, because shutil.copy works fine, but with shutil.move I get
WindowsError: [Error 32] The process cannot access the file because it
is being used by another process
import shutil
import os
path = "G:\Tables\"
dest = "G:\Tables\Soil"
for file in os.listdir(path):
fullpath = os.path.join(path, file)
f = open( fullpath , 'r+')
dataname = f.name
print dataname
shutil.move(fullpath, dest)
del file
I know that the problem is that I don't close the files, but I've already tried it, both with del file and close.file().
Another way I tried is as follows:
import shutil
from os.path import join
source = os.path.join("G:/", "Tables")
dest1 = os.path.join("G:/", "Tables", "Yield")
dest2 = os.path.join("G:/", "Tables", "Soil")
#alternatively
#source = r"G:/Tables/"
#dest1 = r"G:/Tables/Yield"
#dest2 = r"G:/Tables/Soil"
#or
#source = "G:\\Tables\\Millet"
#dest1 = "G:\\Tables\\Millet\\Yield"
#dest2 = "G:\\Tables\\Millet\\Soil"
files = os.listdir(source)
for f in files:
if (f.endswith("harvest.out")):
shutil.move(f, dest1)
elif (f.endswith("sow.out")):
shutil.move(f, dest2)
If I use os.path.join (either using "G:" or "G:/"), then I get
WindowsError: [Error 3] The system cannot find the path specified:
'G:Tables\\Yield/*.*',
If I use forward slashes (source = r"G:/Tables/"), then I get
IOError: [Errno 2] No such file or directory: 'Pepper_harvest.out'*,
I just need one way to move files from one folder to another, that's all...
shutil.move is probably looking in the current working directory for f, rather than the source directory. Try specifying the full path.
for f in files:
if (f.endswith("harvest.out")):
shutil.move(os.path.join(source, f), dest1)
elif (f.endswith("sow.out")):
shutil.move(os.path.join(source, f), dest2)
This should work; let me know if it doesn't:
import os
import shutil
srcdir = r'G:\Tables\\'
destdir = r'G:\Tables\Soil'
for filename in os.listdir(path):
filepath = os.path.join(path, filename)
with open(filepath, 'r') as f:
dataname = f.name
print dataname
shutil.move(fullpath, dest)