Accessing the elements of a list 1 by 1 [duplicate] - python

This question already has answers here:
Perform a string operation for every element in a Python list
(7 answers)
Closed 3 years ago.
I have a variable in list format in which there are number of paths. I want to access each path 1 by 1 to write my output on that path
I have created a list which will have all the paths
folders = glob(test_img_path)
print(folders)
###############OUTPUT of FOLDERS Variable################
['C:\\Python35\\target_non_target\\Target_images_new\\video_tiger_23sec', 'C:\\Python35\\target_non_target\\Target_images_new\\video_tiger_leopard']
####################END#################################
##############LINE ON WHICH THE PATH WILL BE USED TO WRITE OUTPUT######
cv2.imwrite(folders+"\\{}.jpg".format(img_name),image)
###########END############
There will be many paths in this folders variable. How can i modify my code to access these paths 1 by 1 from this list to write my final output on that path

Simply loop through the list and write to the path
folders = glob(test_img_path)
for folder in folders:
image = cv2.imread(...)
...
cv2.imwrite(folder + "\\{}.jpg".format(img_name), image)

Related

Glob files for a range of numbers [duplicate]

This question already has answers here:
How to use glob to read limited set of files with numeric names?
(2 answers)
Closed 3 years ago.
I have a directory of files with names 10.txt, 11.txt .. 29.txt, 30.txt
How can I select files 12 to 21?
Ive tried:
glob.glob('path/[12-21].txt')
Glob is good if you do not know what file names and just need a rough pattern, however, in your case you do know so you might not need to use glob.
It would be better to simply generate your expected list of files and check if they exist eg
from os.path import isfile
# Generate a list of expected file names
expected_files = ["path/{}.txt".format(i) for i in range(12, 22)]
# Filter the list to just the files that actually exist.
actual_files = [f for f in expected_files if isfile(f)]

function that browses every folder in a folder [duplicate]

This question already has answers here:
How to list only top level directories in Python?
(21 answers)
Closed 2 years ago.
How can I bring python to only output directories via os.listdir, while specifying which directory to list via raw_input?
What I have:
file_to_search = raw_input("which file to search?\n>")
dirlist=[]
for filename in os.listdir(file_to_search):
if os.path.isdir(filename) == True:
dirlist.append(filename)
print dirlist
Now this actually works if I input (via raw_input) the current working directory. However, if I put in anything else, the list returns empty. I tried to divide and conquer this problem but individually every code piece works as intended.
that's expected, since os.listdir only returns the names of the files/dirs, so objects are not found, unless you're running it in the current directory.
You have to join to scanned directory to compute the full path for it to work:
for filename in os.listdir(file_to_search):
if os.path.isdir(os.path.join(file_to_search,filename)):
dirlist.append(filename)
note the list comprehension version:
dirlist = [filename for filename in os.listdir(file_to_search) if os.path.isdir(os.path.join(file_to_search,filename))]

How to get the total number of specific files in a directory containing subdirectories? [duplicate]

This question already has answers here:
Find all files in a directory with extension .txt in Python
(25 answers)
Closed 6 years ago.
The following python code counts the number of total files I have in a directory which contains multiple subdirectories. The result prints the subdirectory name along with the number of files it contains.
How can I modify this so that:
It only looks for a specific file extension (i.e. "*.shp")
It provides both the number of ".shp" files in each subdirectory and a final count of all ".shp" files
Here is the code:
import os
path = 'path/to/directory'
folders = ([name for name in os.listdir(path)])
for folder in folders:
contents = os.listdir(os.path.join(path,folder))
print(folder,len(contents))
you can use the .endswith() function on strings. This is handy for recognizing extensions. You could loop through the contents to find these files then as follows.
targets = []
for i in contents:
if i.endswith(extension):
targets.append(i)
print(folder, len(contents))
Thanks for the comments and answer, this is the code I used (feel free to flag my question as a duplicate of the linked question if it is too close):
import os
path = 'path/to/directory'
folders = ([name for name in os.listdir(path)])
targets = []
for folder in folders:
contents = os.listdir(os.path.join(path,folder))
for i in contents:
if i.endswith('.shp'):
targets.append(i)
print(folder, len(contents))
print "Total number of files = " + str(len(targets))

Python - loop through a directory and set a variable to a filename to be manipulated [duplicate]

This question already has answers here:
Iterating through directories with Python
(3 answers)
Closed 8 years ago.
I am trying to loop through a directory and filename into a variable to be manipulated.
Example:
Dir contains:
stuff.txt
home.txt
...
specs.txt
for loop:
var = [filenames in the dir such as stuff,home,spec..]
print hash(var)
Would it be possible to include sub directories?
You could start with something like this using os.listdir:
import os
your_dir = '/home/...' # Dir path
for filename in os.listdir(your_dir):
if os.path.isfile(filename):
print filename
do_something(filename)
With do_something being you hash function and so on.

Read files sequentially in order [duplicate]

This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 9 years ago.
I have a number of files in a folder with names following the convention:
0.1.txt, 0.15.txt, 0.2.txt, 0.25.txt, 0.3.txt, ...
I need to read them one by one and manipulate the data inside them. Currently I open each file with the command:
import os
# This is the path where all the files are stored.
folder path = '/home/user/some_folder/'
# Open one of the files,
for data_file in os.listdir(folder_path):
...
Unfortunately this reads the files in no particular order (not sure how it picks them) and I need to read them starting with the one having the minimum number as a filename, then the one with the immediate larger number and so on until the last one.
A simple example using sorted() that returns a new sorted list.
import os
# This is the path where all the files are stored.
folder_path = 'c:\\'
# Open one of the files,
for data_file in sorted(os.listdir(folder_path)):
print data_file
You can read more here at the Docs
Edit for natural sorting:
If you are looking for natural sorting you can see this great post by #unutbu

Categories

Resources