I am trying to write a program that will delete files inside a specific folder.
When I run the following code, I get the error:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/joshuamorse/Documents/Programming/python/deletefiles/1.txt
My code:
import os, sys
for filename in os.listdir('/Users/joshuamorse/Documents/programming/python/deletefiles/f2d/'):
print(filename)
x = os.path.realpath(filename) #not required but included so program would give more meaningful error
os.unlink(x)
when line 5 is commented out the program runs fine and lists all the files contained in the folder.
I do not understand why the error is cutting off the last folder (f2d) in the directory path. Additionally if I miss type the last folder in the path to something like f2 it produces the following error: FileNotFoundError: [Errno 2] No such file or directory: '/Users/joshuamorse/Documents/programming/python/deletefiles/f2/.
Why is the last folder included in the path only when it is mispelled? How would I go about fixing this so the correct path is passed?
Solution
Provided by #ekhumoro
os.listdir() does not return the path, just the files names in the specified folder.
Corrected Code
import os
dirpath = '/Users/joshuamorse/Documents/programming/python/deletefiles/f2d/'
for filename in os.listdir(dirpath):
x = os.path.join(dirpath, filename)
os.unlink(x)
Related
I want to move all the files from multiple subdirectories to another folder in the same directory as the parent folder but get the following error:
FileNotFoundError: [Errno 2] No such file or directory: '/content/drive/MyDrive/Dev/FaceRec/lfw/Emmit_Smith/Emmit_Smith_0001.jpg' -> '/content/drive/MyDrive/Dev/FaceRec/negatives/Emmit_Smith_0001.jpg'
this is my code:
for directory in os.listdir('/content/drive/MyDrive/Dev/FaceRec/lfw'):
for file in os.listdir(os.path.join('/content/drive/MyDrive/Dev/FaceRec/lfw', directory)):
path = os.path.join('/content/drive/MyDrive/Dev/FaceRec/lfw', directory, file)
new_path = os.path.join('/content/drive/MyDrive/Dev/FaceRec/negatives', file)
os.replace(path, new_path)
Thank you for the help in advance
Try the following:
import os
import glob
import shutil
src_path = '/content/drive/MyDrive/Dev/FaceRec/lfw'
dest_path = src_path.replace('lfw', 'negatives')
flist = glob.glob(os.path.join(src_path, '*/*'))
for fname in flist:
shutil.move(fname, fname.replace(os.path.dirname(fname), dest_path))
Why this is better:
The glob functions helps to avoid one for loop and also prevents from repeatedly joining the paths together
shutil.movecreates the destination directory for you if it does not exist. Also it can handle symlinks.
By putting the paths in variables we can minimize copy past errors
I want to read data from specific files from a directory whose structure is as follows:
-Directory
-Subdirectory1
-AGreek.srt
-AEnglish.srt
-Subdirectory2
-BGreek.srt
-BEnglish.srt
-test.py
Where test.py is my script and I'm supposed to read only the english files from the Directory. This is my current script:
import os
substring = 'English.srt'
for root, subdirs, files in os.walk('Directory'):
for filename in files:
if substring in filename:
fp = open(os.path.abspath(filename))
# Further Action
However this is giving me the following error:
FileNotFoundError: [Errno 2] No such file or directory: '/home/coder/Spam/AEnglish.srt'
How do I resolve the error? (P.s.: Spam is the folder inside which Directory and test.py are located)
You need to use os.path.join(root,filename) to access the file.
Ex:
import os
substring = 'English.srt'
for root, subdirs, files in os.walk('Directory'):
for filename in files:
if substring in filename:
fp = open(os.path.join(root,filename))
# Further Action
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)
I'm writing a script that walks through a directory and looks for files with the typical Windows installer extensions and deletes them. When I run this with a list (vs say checking for .msi or .exe), it breaks when going through the nested loop again. It seems as if it runs though my list, deletes one type of extension then runs through the loop again and attemtps to find the same extension then throws an exception. Here is the output when I simply print, but not remove a file:
> C:\Users\User\Documents\Python Scripts>python test.py < test_run.txt
> Found directory: . Found directory: .\test_files
> Deleting test.cub
> Deleting test.idt
> Deleting test.idt
> Deleting test.msi
> Deleting test.msm
> Deleting test.msp
> Deleting test.mst
> Deleting test.pcp
> Deleting test1.exe
When I attempt to run it with os.remove it gives the following:
Found directory: .
Found directory: .\test_files
Deleting test.cub
Traceback (most recent call last):
File "test.py", line 13, in <module>
os.remove(fileName)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'test.cub'
I read up on os walk and that seems to be working properly, I can't seem to figure out where this script is going wrong. The code is below:
import os
myList = [".msi", ".msm", ".msp", ".mst", ".idt", ".idt", ".cub", ".pcp", ".exe"]
rootDir = '.'
for dirName, subdrList, fileList in os.walk(rootDir):
print('Found directory: %s' %dirName)
for fileName in fileList:
for extName in myList:
if(fileName.endswith(extName)):
print('\t Deleting %s' % fileName)
os.remove(fileName)
The correct relative name of the file test.cub is .\test_files\test.cub.
The relative name you are supplying is .\test.cub.
As it says in the os.walk documentation:
To get a full path (which begins with top) to a file or directory in
dirpath, do os.path.join(dirpath, name).
Probably a very noob question..
But
When I try:
f = open(os.path.join(os.path.dirname(__file__), filename),"w")
I get an error
IOError: [Errno 2] No such file or directory: '/home/path/filename'
Isnt it that since i have said "w" .. it will write a new file if its not there already?
The error message can be reproduced like this:
import os
filename = '/home/path/filename'
f = open(os.path.join(os.path.dirname(__file__), filename),"w")
f.close()
# IOError: [Errno 2] No such file or directory: '/home/path/filename'
The problem here is that filename is an absolute path, so
os.path.join ignores the first argument and returns filename:
In [20]: filename = '/home/path/filename'
In [21]: os.path.join(os.path.dirname(__file__), filename)
Out[21]: '/home/path/filename'
Thus, you are specifying not only a file that does not exist, you are specifying a directory that does not exist. open refuses to create the directory.
Are you trying to literally write home/path/filename? In that case, it's complaining that /home/path doesn't exist. Try creating a directory named /home/path or choosing a file name inside a directory that already exists (for example, find out what the path is to your actual home directory.) You can also use relative paths. See
http://en.wikipedia.org/wiki/Path_%28computing%29
for the difference between absolute and relative paths.