Python glob return empty array, why? - python

I have this simple Python code which supposed to return files in path. But it returns an empty list all the time. Why ?
My array path is correct.
import glob
flowers_path = 'C:/flower_v1/training-images/*/*.jpg'
addrs = glob.glob(flowers_path)
print(addrs)
Returns :
[]
My directory structure :
I am doing the execution on Google Collab.

You aren't quite getting the glob syntax right. You should try this:
import glob
flowers_path = 'C:/flower_v1/training-images/**/*.jpg' # ** is for going through directories
address = glob.glob(flowers_path, recursive=True) # recursive flag must be true
print(address)
or simply
address = glob.glob('/**/*.jpg',recursive=True)

Related

Creating Modules and using them

I am playing around with creating modules.I have two python scripts.The first (the module) has:
def abspath(relpath):
import os
absdir = os.path.realpath('__file__')
absdir = absdir.split('_')[0].replace('\\', '/')
filename = str(absdir + relpath )
print (filename)
return filename;
The second file (main) has:
import file_tools as ft
filename = ft.abspath('some/path/')
When I run Main, filename appears empty (Type:None). I have run the filename = abspath(etc) within the 'module', and it works. Clearly, I am missing something here!!
and doing this, so any help would be useful.
Thank's all.
MT
The problem lies in how you're finding the working directory; the preferred method being os.getcwd() (or os.getcwdb for Unix compatibility). Using that, we can see that your function boils down to:
def abspath(relpath):
return os.path.join(os.getcwd(), relpath)

How to get parent folder name of current directory?

I know there are functions for finding parent directory or path such as.
os.path.dirname(os.path.realpath(__file__))
'C:\Users\jahon\Desktop\Projects\CAA\Result\caa\project_folder'
Is there a function that just returns the parent folder name? In this case it should be project_folder.
You can achieve this easily with os
import os
os.path.basename(os.getcwd())
You can get the last part of any path using basename (from os.path):
>>> from os.path import basename
>>> basename('/path/to/directory')
'directory'
Just to note, if your path ends with / then the last part of the path is empty:
>>> basename('/path/to/directory/')
''
Yes, you can use PurePath.
PurePath(__file__).parent.name == 'parent_dir'
You can use split and os.path.sep to get the list of path elements and then call the last element of the list:
import os
path = 'C:\\Users\\jahon\\Desktop\\Projects\\CAA\\Result\\caa\\project_folder'
if path.split(os.path.sep)[-1]:
parent_folder = path.split(os.path.sep)[-1] # if no backslashes at the end
else:
parent_folder = path.split(os.path.sep)[-2] # with backslashes at the end

Removing elements from list and importing list into another code

I'm trying to list all the html files in a single directory which works fine. However I'm trying to remove everything that is not a html file from that list as well.
i have 8 files called 1, 2, 3... etc. and 6.htmxl (remove) and pipe.sh.save(remove)
The code I made removes the .htmxl file but does not remove the .sh.save file from the list.
from os import listdir
from os.path import isfile, join
import pyimport
import time
def main():
onlyfiles = [f for f in listdir('/home/pi/keyboard/html') if isfile(join('/home/pi/keyboard/html',f)) ]
j = 0
print len(onlyfiles)
for i in onlyfiles:
if i.find(".html") == -1:
print i
print "not a html"
j = onlyfiles.index(i)
print j
del onlyfiles[j]
else:
print i
print "html found"
time.sleep(0.5)
outfiles = onlyfiles
print outfiles
return outfiles
if __name__ == "__main__":
main()
I also have another code which is suppose to get the "outfiles" list
import server_handler
files = server_handler.main()
fileList = server_handler.outfiles
But when I run it I get:
AttributeError: 'module' object has no attribute 'outfiles'
I'm running nearly the exact same code on another code which is creating 'output' and I import it in the exact same way so I'm not sure why its not importing correctly.
You might find the following approach more suitable, it uses Python's glob module:
import glob
print glob.glob('/home/pi/keyboard/html/*.html')
This will return you a list of all files in that folder ending in .html automatically.
Replace i.find(".html") with i.endswith(".html"). Now you should get only HTML files (or more precisely only files that look like HTML).
For the second part - remove:
fileList = server_handler.outfiles
server_handler.main() already returns the list so you have it in files. The last line doesn't make any sense.
EDIT:
Martin's answer has better way to get files. So I recommend you use his advice and not mine :).
This would work if main was a class, and you used
class main():
def __init__(self):
....
self.outfiles = onlyfiles
return self.outfiles

How to move down to a parent directory in Python?

The following code in Python gives me the current path.
import os
DIR = os.path.dirname(os.path.dirname(__file__))
How can I now use the variable DIR to go down one more directory? I don't want to change the value of DIR as it is used elsewhere.
I have tried this:
DIR + "../path/"
But it does not seems to work.
Call one more dirname:
os.path.join(os.path.dirname(DIR), 'path')
Try:
import os.path
print(os.path.abspath(os.path.join(DIR, os.pardir)))
When you join a path via '+' you have to add a 'r':
path = r'C:/home/' + r'user/dekstop'
or write double backslashes:
path = 'C://home//' + 'user//dekstop'
Anyway you should never use that!
That's the best way:
import os
path = os.path.join('C:/home/', 'user/dekstop')

PYTHON: Searching for a file name from an array and then relocating the file

I'm new to Python and could really use some help. I have a large collection of images that I'm sorting. I need every 260th image (for example: 0, 260, 520, 780, etc). I then need to relocate those images to a new folder. Here is my code so far:
import os, os.path, sys, shutil
root = '.'
dst = "/Users/Desktop"
print "/////// F I N D__A L L__F I L E S __W I T H I N __R A N G E ///////////////////"
selectPhotos = range(260, 213921)
print selectPhotos[::260]
print "/////// L I S T__O F __A L L __J P E G S ///////////////////"
for files in os.listdir("/Users/Desktop/spaceOddy/"):
#if files.endswith(".jpg"):
# print files
if files.startswith(selectPhotos[]):
print files
shutil.move ("files", root)
My code isn't working in two places.
I receive an error that I need to pass a tuple into startswith, which I don't know how to do. I know what a tuple is but in terms of syntax I'm in the dark.
I don't know much about shutil.move. If anyone knows of a better approach I'd appreciate it.
Thanks,
To move every nth image file in a directory to another directory:
#!/usr/bin/env python
from __future__ import print_function
import glob
import shutil
import sys
dstdir = "/Users/Desktop"
for file in glob.glob("/Users/Desktop/spaceOddy/*.jpg")[::260]:
try:
shutil.move(file, dstdir)
except EnvironmentError as e:
print("can't move {}, error {}".format(file, e), file=sys.stderr)
Start here.
import os, shutil
root = '.'
src = "/Users/Desktop/spaceOddy/"
dst = "/Users/Desktop"
for i, filename in enumerate(os.listdir(src)):
if i%260 == 0:
print filename
shutil.move (src + filename, root)
I've changed files to filename. Inside the loop, filename is a string: the name of single file in the directory.
I used enumerate, which gives us both the name of a file and a counter starting at 0. Try something like print enumerate(['cat', 'dog', 'pig']) in a shell to see what it does.
Now that we have a counter, I used the test i%260 == 0 to choose only ever 260th file.
If you need to get every 260th .jpg file, change the if statement to if i%260==0 and filename.endswith('.jpg')
I don't know what you were trying to do with startswith, but you need to pass it a string as an argument if you want to use it, not a tuple.
print selectPhotos[::260] doesn't actually change selectPhotos. You may not actually need it in this case, but for the future... you can pass a step value to range like this selectPhotos = range(0,213921,260) or to change selectPhotos after creating it, use selectPhotos = selectPhotos[::260]

Categories

Resources