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).
Related
I am taking an online course in Python. I am using version 3.8.1 on Windows. I am trying to write a program which will retrieve the size of all the files within a certain folder. My current working directory is 'c:\'. This is the code I have written:
for filename in os.listdir('c:\\mypythonscripts'):
if not os.path.isfile(os.path.join('c:\\mypythonscripts', filename)):
continue
totalSize = totalSize + os.path.getsize(os.path.join('c:\\mypythonscripts', filename))
This is the error message it produces:
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
for filename in os.listdir('c:\\mypythonscripts'):
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'c:\\mypythonscripts'
The spelling of the file name is correct and I am able to retrieve the file size when I use an absolute path:
for filename in os.listdir('c:\\users\\owner\\mypythonscripts'):
if not os.path.isfile(os.path.join('c:\\users\\owner\\mypythonscripts', filename)):
continue
totalSize = totalSize + os.path.getsize(os.path.join('c:\\users\\owner\\mypythonscripts', filename))
>>> totalSize
2281314
Can someone tell me what is preventing Python from recognizing the relative path?
If you're running the script from the mypythonscripts directory you can go os.listdir('.').
If you're running the script from the owner directory, you can go os.listdir('mypythonscripts').
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)
I'm slowly starting to study about python and wanted to write simple script which use tinify api, takes photos from unoptimalized directiory, compress it and put to optimalized directory. So far works partly, I mean weirdly I need to keep photos in main directory and unoptimalized one. If I dont have another copy in one of these directories, I have error. another thing is that after I launch script, only first photo is compressed and put inside optimalized directory, and then error appears.
So far I'm experimenting on two photos: lew.jpg and kot.jpg
My directory structure is like this:
Main root directory with script, and two other directories inside (optimalized and unoptimalized)
def optimalizeImages():
for fname in os.listdir('./unoptimalized'):
if fname.endswith(".jpg"):
print(fname)
source = tinify.from_file(fname)
print("processing", fname)
os.chdir("./optimalized")
source.to_file("optimalized-" + fname)
print("changed", fname)
optimalizeImages()
Error after processing first image:
Traceback (most recent call last):
File "python.py", line 20, in <module>
optimalizeImages()
File "python.py", line 11, in optimalizeImages
source = tinify.from_file(fname)
File "/home/grzymowiczma/.local/lib/python2.7/site-packages/tinify/__init__.py", line 79, in from_file
return Source.from_file(path)
File "/home/grzymowiczma/.local/lib/python2.7/site-packages/tinify/source.py", line 13, in from_file
with open(path, 'rb') as f:
IOError: [Errno 2] No such file or directory: 'kot.jpg'
and if i keep photos only in root directory, no error but also no any action, if i keep them only in unoptimalized i get same error:
Traceback (most recent call last):
File "python.py", line 20, in <module>
optimalizeImages()
File "python.py", line 11, in optimalizeImages
source = tinify.from_file(fname)
File "/home/grzymowiczma/.local/lib/python2.7/site-packages/tinify/__init__.py", line 79, in from_file
return Source.from_file(path)
File "/home/grzymowiczma/.local/lib/python2.7/site-packages/tinify/source.py", line 13, in from_file
with open(path, 'rb') as f:
IOError: [Errno 2] No such file or directory: 'lew.jpg'
There are two issues here, both because you are using relative filenames. os.listdir() gives you those relative filenames, without a path. Instead of ./unoptimalized/kot.jpg, you get just kot.jpg.
So when you try to load the image:
source = tinify.from_file(fname)
you tell the library to load image.jpg without any context other than the current working directory. And that's not the right directory, not if os.listdir('./unoptimalized') worked to list all image files; that indicates that the current working directory is in the parent directory of both unoptimalized and optimalized.
You solved that by putting an image file with the same name in the parent directory, but that's not quite the right way to solve this. More on this below.
The next issue is that you change the working directory:
os.chdir("./optimalized")
You do this for the first image, so now the current working directory has changed to optimalized. When you then loop back up for the next file, you are now in the wrong location altogether to read the next file. Now lew.jpg, which might exist in ./unoptimalized or the parent directory, can't be found because it is not there in ./optimalized.
The solution is to add on the directory name. You can do so with os.path.join(), and not changing directories:
def optimalizeImages():
input_dir = './unoptimalized'
output_dir = './optimalized'
for fname in os.listdir(input_dir):
if fname.endswith(".jpg"):
print(fname)
source = tinify.from_file(os.path.join(input_dir, fname))
print("processing", fname)
source.to_file(os.path.join(output_dir, "optimalized-" + fname))
print("changed", fname)
Note that this still depends heavily on the current working directory being correct, but at least it is now stable and stays at the parent directory of both optimalized and unoptimalized. You may want to change that to using absolute paths.
And a side note on language: In English, the correct spelling of the two terms is optimized and unoptimized. I didn't correct those in my answer to keep the focus on what is going wrong.
I am trying to create a script which will automatically move my scanned lecture notes from specific dates to a folder.
To do this I need to sort the files on order of their upload date, which is their mdate.
The problem I am having is that the script does find the files and puts them in a list, but the os.path.mtime() command fails to find those same files.
Here is my code:
import os
p="someDir"
if os.path.isdir(p):
files = os.listdir(p)
print("Files found in folder:", files)
files.sort(key=os.path.getmtime)
And this is the error I am getting:
Files found in folder: ['20180907.pdf', '20180831.pdf',
'20180905.pdf', '20180906.pdf']
Traceback (most recent call last):
File "/home/mats/Google Drive/Programmering/Python/Python
Projects/homework/homework.py", line 32, in <module>
files.sort(key=os.path.getmtime)
File "/usr/lib/python3.6/genericpath.py", line 55, in getmtime
return os.stat(filename).st_mtime
FileNotFoundError: [Errno 2] No such file or directory: '20180907.pdf'
Your variable files contains:
['20180907.pdf', '20180831.pdf',
'20180905.pdf', '20180906.pdf']
Which is not the path in absolute/relative in regards to the working directory. The path also includes the folder!
2 solutions: 1 you sort the list containing the path names, i.e:
from os.path import join
files = [join(p, elt) for elt in files]
Or you change the working directory in the loop, i.e. instead of the print:
os.chdir(p)
I'm trying to build a little renaming program to help save me time in the future.
Basically it will go through directories I point it too and rename files if they meet certain criteria.
I have written what I need but I have a bug in the very beginning that I can't figure out.
Here is the code:
import os
import fnmatch
for file in os.listdir("""/Users/Desktop/TESTME"""):
if fnmatch.fnmatch(file,'MISC*'):
os.rename(file, file[4:12] + '-13-Misc.jpg')
When I try to run it I am getting this:
Traceback (most recent call last):
File "/Users/Documents/Try.py", line 6, in <module>
os.rename(file, file[4:12] + '-13-Misc.jpg')
OSError: [Errno 2] No such file or directory
I also tried this:
if fnmatch.fnmatch(file,'MISC*'):
fun = file[4:12] + '-13-Misc.jpg'
os.rename(file, fun)
But I get the same thing.
It's not recognizing the file as a file.
Am I going about this the wrong way?
You'll need to include the full path to the filenames you are trying to rename:
import os
import fnmatch
directory = "/Users/Desktop/TESTME"
for file in os.listdir(directory):
if fnmatch.fnmatch(file, 'MISC*'):
path = os.path.join(directory, file)
target = os.path.join(directory, file[4:12] + '-13-Misc.jpg'
os.rename(path, target)
The os.path.join function intelligently joins path elements into a whole, using the correct directory separator for your platform.
The function os.listdir() only returns the file names of the files in the given directory, not their full paths. You can use os.path.join(directory, file_name) to reconstruct the full path of the file.
You could also do this in bash:
cd /Users/Desktop/TESTME/
for f in MISC*; do mv "$f" "${f:4:8}-13-Misc.jpg"; done