Python list different directory without chdir [duplicate] - python

This question already has answers here:
How do I list all files of a directory?
(21 answers)
Closed 3 years ago.
I have a directory with my .py file and I have another directory where I am writing files to. How can I get a os.listdir of the second directory without using os.chdir?
Edit: Sorry seems like there are 2 parts to my implementation. My current code is this:
files = [f for f in os.listdir(2nd_d) if os.path.isfile(f)]
It currently returns an empty list when there are some files in the directory.

Just use the full path of that other directory.
dir1_contents = os.listdir('C://path/to/my/dir1')
dir2_contents = os.listdir('C://path/to/my/dir2')

Why not just do a full path check?
import numpy as np
import os
base = 'C:/Users/user/desktop/files/'
for i in range(50):
temp = np.random.normal(0, 1, (100, 100))
np.save(f'{base}File_{i}.npy', temp)
files = os.listdir(base)

Related

Apply script to multiple folders using string in file path [duplicate]

This question already has answers here:
How to use glob() to find files recursively?
(28 answers)
Closed 1 year ago.
I am new to the programing world and I have hit a snag on a piece of code.
What I have: I have a piece of code that identifies all .MP4 files and calculates the size of the files within a directory. So far I can only apply this code to a specific folder that I input manually. But the code works.
Problem: I would like to apply what I have to multiple folders within a directory. I have several folders with years in the file path and I would like to apply this code to each year individually. For example: I need a piece of code/direction to code that can allow me to run this code on all folders with '2021' in the name.
Any pointers or suggestions are welcome.
# import module
import os
# assign size
size = 0
# assign folder path
Folderpath = r'C:\file_path_name_here'
# get size
for path, dirs, files in os.walk(Folderpath):
for f in files:
if not f.endswith('.MP4'):
continue
else:
fp = os.path.join(path, f)
size += os.path.getsize(fp)
# display size
print("Folder size: " + str(size))
You can use glob for that.
If i understand you correctly you want to iterate through all Folders right?
I myself am not a routined coder aswell but i use it in for a Script where i have to iterate over an unknown number of files and folders. In my case PDF's
which then get scanned/indexed/merged...
This obviously returns a list of of files with which you then could workd through. os.path commonpath is also handy for that.
def getpdflisting(fpath):
filelist = []
for filepath in Path(os.path.join(config['Ordner']['path'] +\
fpath)).glob('**/*.pdf'):
filelist.append(str(filepath))
if filelist:
filelist = [x for x in filelist if x]
logger.info(filelist)
return filelist
Or even better https://stackoverflow.com/a/66042729/16573616

printing all the ".lnk" filenames in foldes and sub folders [duplicate]

This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 2 years ago.
so there are alot of files with .lnk extension in the start menu folder C:\ProgramData\Microsoft\Windows\Start Menu\Programs i want to print all those file names so i tried this code:
import os
import glob
startmenu = r'C:\ProgramData\Microsoft\Windows\Start Menu\Programs'
os.chdir(startmenu)
for file in glob.glob("**/*.lnk", recursive = True):
print(file)
it prints the link to the files, but i want to print only the file names with the extension of ".lnk"
Convert the absolute path to list then take the last element from the list. See the below code.
import os
import glob
startmenu = r'C:\ProgramData\Microsoft\Windows\Start Menu\Programs'
os.chdir(startmenu)
for file in glob.glob("**/*.lnk", recursive=True):
print(os.path.split(file)[-1])

Keep names of subfolders in a list [duplicate]

This question already has answers here:
How do I list all files of a directory?
(21 answers)
Closed 4 years ago.
In this a variable there is a folder called main_folder.
This folder has two folders:
111,222
I need to get the names of these folders in a list.
Tried this:
a = r'C:\Users\user\Desktop\main_folder'
import os
for root, dirs, files in os.walk(a):
print(dirs)
gives:
['111', '222'] # <--------------This only needed
[]
[]
How to keep only the first list and not the empty ones which I think describe the contents of these folders since they don't have folders.
This function will do the job:
import os
def get_immediate_subdirectories(a_dir): ##a_dir is the path of the main folder
return [name for name in os.listdir(a_dir) ## returns all the immediate subfolders
if os.path.isdir(os.path.join(a_dir, name))] ## keeps checking the name + file is here
Calling Function:
get_immediate_subdirectories("Path")
Iterate just once via next:
import os
a = r'C:\Users\user\Desktop\main_folder'
walker = os.walk(a)
res = next((dirs for _, dirs, _ in walker), [])
If necessary, you can continue iterating walker via additional next calls.

Make a List for sub directories path [duplicate]

This question already has answers here:
Getting a list of all subdirectories in the current directory
(34 answers)
Closed 7 years ago.
I have a directory and I need to make a path list for the sub directories.
For example my main directory is
C:\A
which contains four different sub directories : A1,A2,A3,A4
I need a list like this:
Path_List = ["C:\A\A1","C:\A\A2","C:\A\A3","C:\A\A4"]
Cheers
import os
base_dir = os.getcwd()
sub_dirs = [os.path.join(base_dir, d) for d in os.listdir(base_dir)]
You could (and should, i think) use os module, wich is easy to use and provides a lot of stuff to deal with paths.
I wont say anymore, because your question is vague and shows no effort on searching. You are welcome!!
sub_dirs = os.listdir(os.getcwd()) ## Assuming you start the script in C:/A
path_list = []
for i in sub_dirs:
path_list.append(os.path.join(os.getcwd(),i))
Dirty and fast.

Automatically creating a list in Python [duplicate]

This question already has answers here:
How do I list all files of a directory?
(21 answers)
Closed 8 years ago.
My code:
red_images = 'DDtest/210red.png'
green_images = 'DDtest/183green.png'
b = [red_images, green_images]
shuffle(b)
I have several hundred pictures, and in hopes of making my code as concise as possible (and to expand my python knowledge), I was wondering how I write code that automatically takes the files in a folder and makes them a list.
I have done similar things in R, but I'm not sure how to do it in python.
You can also use os:
import os
from random import shuffle
# Base directory from which you want to search
base_dir = "/path/to/whatever"
# Only take the files in the above directory
files = [f for f in os.listdir(base_dir)
if os.path.isfile(os.path.join(base_dir, f))]
# shuffle (in place)
shuffle(files)
import glob
my_new_list = glob.glob("/your/folder/*")

Categories