I am trying to get the code to list all the directories in a folder, change directory into that folder and get the name of the current folder. The code I have so far is below and isn't working at the minute. I seem to be getting the parent folder name.
import os for directories in os.listdir(os.getcwd()): dir = os.path.join('/home/user/workspace', directories) os.chdir(dir) current = os.path.dirname(dir) new = str(current).split("-")[0] print new
I also have other files in the folder but I do not want to list them. I have tried the below code but I haven't got it working yet either.
for directories in os.path.isdir(os.listdir(os.getcwd())):
Can anyone see where I am going wrong?
Thanks
Got it working but it seems a bit round about.
import os os.chdir('/home/user/workspace') all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)] for dirs in all_subdirs: dir = os.path.join('/home/user/workspace', dirs) os.chdir(dir) current = os.getcwd() new = str(current).split("/")[4] print new
Linux or UNIX-like system use the ls command to list files and directories. However, ls does not have an option to list only directories. You can use combination of ls command, find command, and grep command to list directory names only. You can use the find command too.
The ls command is used to list files or directories in Linux and other Unix-based operating systems. Just like you navigate in your File explorer or Finder with a GUI, the ls command allows you to list all files or directories in the current directory by default, and further interact with them via the command line.
You can use the DIR command by itself (just type “dir” at the Command Prompt) to list the files and folders in the current directory.
This will print all the subdirectories of the current directory:
print [name for name in os.listdir(".") if os.path.isdir(name)]
I'm not sure what you're doing with split("-")
, but perhaps this code will help you find a solution?
If you want the full pathnames of the directories, use abspath
:
print [os.path.abspath(name) for name in os.listdir(".") if os.path.isdir(name)]
Note that these pieces of code will only get the immediate subdirectories. If you want sub-sub-directories and so on, you should use walk
as others have suggested.
import os for root, dirs, files in os.walk(top, topdown=False): for name in dirs: print os.path.join(root, name)
Walk is a good built-in for what you are doing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With