In my code in Python I keep getting the error
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Z_Cawc_000_005_estimated_value.tfw' -> 'awc_000_005_estimated_value.tfw'
So,
'Z_Cawc_000_005_estimated_value.tfw' is the name of the first raster on a folder with 800 rasters.
All I want is to get rid off the initial "Z_C" characters of the 800 raster files in a folder.
My code is
import os
path = os.getcwd()
filenames =
os.listdir(r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats')
for filename in filenames:
os.rename(filename, filename.replace("Z_C",""))
I`ve also try the following code:
from os import rename, listdir
badprefix = "Z_C"
fnames = listdir('I:\\PhD_2019\\Spatial_Datasets\\Baroon_Pocket_Dam_Catchment\\Raster\\Soil_Zonal_Stats')
for fname in fnames:
if fname.startswith(badprefix):
rename(fname, fname.replace(badprefix, '', 1))
and the following code as well:
import os
path = os.getcwd()
filenames = os.listdir(r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats' )
for filename in filenames:
os.rename(filename, filename.replace("Z_C", ""))
But both of them resulted in the same error!
Can anyone let me know what is wrong with my code, please?
You need to specify the full path to the file, otherwise python would look in your working directory and won't find the file. the fix is:
folder = r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats'
filenames =
os.listdir(r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats')
for filename in filenames:
os.rename(os.path.join(folder, filename), os.path.join(folder, filename.replace("Z_C","")))
Related
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).
you will find my code i am not python pro but i do everything to become it
import os, sys
os.listdir(os.getcwd())
Out[3]: ['.ipynb_checkpoints',
'helmet_10_0.png',
'helmet_10_1.png',
'helmet_10_10.png',
I wish
Out[0]: ['casque_Chantier_10_0.png',
'casque_Chantier_10_10.png',
'casque_Chantier_10_100.png'
so on
source = 'D:\\Chasse_Au_tressor\\base_agmt\\extractedFrames_step_5\\helmet_10_0.png'
dest = 'D:\\Chasse_Au_tressor\\base_agmt\\extractedFrames_step_5\\Casque_Chantier_10_0.png'
os.rename(source, dest)
Out[2]: ['casque_Chantier_10_0.png',
'helmet_10_1.png',
'helmet_10_10.png',
'helmet_10_100.png',
'helmet_10_101.png',
I can't make a loop which takes all the files with 'glob' and renames them
<ipython-input-33-1a271eebe4a0> in <module>
1 for i in source:
2 if i != dest:
----> 3 os.rename(i,dest)
FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable: 'D' -> 'D:\\Chasse_Au_tressor\\base_agmt\\extractedFrames_step_5\\Casque_Chantier_{*}.png'
I want the images on casque_Chantier_{index=1}.png
Try this. You can just rename the file name instead of opening it and renaming it once again which will save memory while performing the action on multiple files in a for loop. This will also make sure that only the intended files i.e. file names which start with "helmet" alone are renamed
#Import package
import os
#Loop through the file names
for filename in os.listdir(os.getcwd()):
if filename.startswith("helmet_"):
os.rename(filename, "casque_Chantier_"+filename[7:])
Cheers!
The following code iterates through each file and renames the file as required. It replaces the "helmet_" part with "casque_Chantier_".
I have set this up so that it runs in the same folder as the files to be renamed.
import os
for file in os.listdir():
os.rename(file, file.replace("helmet_","casque_Chantier_")
import os, sys
directory = os.getcwd()
filenames = os.listdir(directory)
renamed_filenames = [f.replace('helmet', 'casque_Chantier') for f in filenames]
for i in range(len(filenames)):
source_filepath = os.path.join(directory, filenames[i])
dest_filepath = os.path.join(directory, renamed_filenames[i])
os.rename(source_filepath, dest_filepath)
The following works for python 3.6
You will need replace from string library to change 'helmet' into 'casque_Chantier' :
import shutil
import os
dir_path = os.getcwd()
for filename in os.listdir(dir_path):
src = os.path.join(dir_path, filename)
dst = os.path.join(dir_path, filename.replace("helmet", "casque_Chantier"))
shutil.move(src, dst)
I'm trying to slice a bunch of images from a directory. Try to loop over them, but I'm getting FileNotFoundError: [Errno 2] No such file or directory: '45678.png'
Actually, that's the name of one of the files. This is my code:
import image_slicer
import os
indir = '/Users/data/h3'
for root, dirs, filenames in os.walk(indir):
for file in filenames:
if file.endswith('.png'):
image_slicer.slice(file, 4)
Dir is ok, I don't get why cannot find the file, when actually finds it as per the error message
You need to add the path to the filename when you open it with slice().
Try image_slicer.slice(os.path.join(dirpath, name), 4)
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'.
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)