function that browses every folder in a folder [duplicate] - python

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))]

Related

Reading text files paths with the same order of them in the directory in Python [duplicate]

This question already has answers here:
Non-alphanumeric list order from os.listdir()
(14 answers)
Closed 1 year ago.
directory = r'/home/bugramatik/Desktop/Folder'
for filename in os.listdir(directory):
file = open('/home/bugramatik/Desktop/Folder'+filename,'r')
print(BinaryToString(file.read().replace(" ","")))
I want to read all files inside of the a folder same order with folder structure.
For example my folder is like
a
b
c
d
But when I run the program at above it shows like
c
a
d
b
How can I read it like a,b,c,d?
The order in os.listdir() is actually more correct. But if you want to open the files in alphabetical order, like ls displays them, just reimplement the sorting it does.
for filename in sorted(os.listdir(directory)):
with open(os.path.join(directory, filename) ,'r') as file:
print(BinaryToString(file.read().replace(" ","")))
Notice the addition of sorted() and also the use of os.path.join() to produce an actually correct OS-independent file name for open(), and the use of a with context manager to fix the bug where you forgot to close the files you opened. (You can leave a few open just fine, but the program will crash with an exception when you have more files because the OS limits how many open files you can have.)

Rename part of the name in any files or directories in Python [duplicate]

This question already has answers here:
How to rename a file using Python
(17 answers)
Closed 3 years ago.
I have a root folder with several folders and files and I need to use Python to rename all matching correspondences. For example, I want to rename files and folders that contain the word "test" and replace with "earth"
I'm using Ubuntu Server 18.04. I already tried some codes. But I'll leave the last one I tried. I think this is really easy to do but I don't have almost any knowledge in py and this is the only solution I have currently.
import os
def replace(fpath, test, earth):
for path, subdirs, files in os.walk(fpath):
for name in files:
if(test.lower() in name.lower()):
os.rename(os.path.join(path,name), os.path.join(path,
name.lower().replace(test,earth)))
Is expected to go through all files and folders and change the name from test to earth
Here's some working code for you:
def replace(fpath):
filenames = os.listdir()
os.chdir(fpath)
for file in filenames:
if '.' not in file:
replace(file)
os.rename(file, file.replace('test', 'earth'))
Here's an explanation of the code:
First we get a list of the filenames in the directory
After that we switch to the desired folder
Then we iterate through the filenames
The program will try to replace any instances of 'test' in each filename with 'earth'
Then it will rename the files with 'test' in the name to the version with 'test' replaced
If the file it is currently iterating over is a folder, it runs the function again with the new folder, but after that is done it will revert back to the original
Edited to add recursive iteration through subfolders.

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

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)

List directories python OSX [duplicate]

This question already has answers here:
os.makedirs doesn't understand "~" in my path
(3 answers)
Closed 7 years ago.
I am having an issue with trying to list all of the files/folders within a directory with Python 2.6, on Mac OS X.
To simplify the problem, I am attempting to simply list all the files on my desktop (which is not empty). I understand this can be done like this:
currentFileList = os.listdir("~/Desktop")
But I am getting the error:
currentFileList = os.listdir("~/Desktop")
OSError: [Errno 2] No such file or directory: '~/Desktop'
Any suggestions?
You should pass absolute pass to os.listdir function. You can use os.expanduser function to expand ~:
os.listdir(os.path.expanduser('~/Desktop'))
By the way. Be careful: ~foobar will replace the path with home folder for user foobar (e.g. /home/foobar)
You need the full path not relative
os.listdir('/Users/YOURUSERNAME/Desktop')

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