Ubuntu 16.04下os.walk获取子目录为空问题求助
folders List in Ubuntu with os.walk() Hey there! Let's break down why your code works on Windows but not Ubuntu, and how to fix it quickly.
The Root Cause
On Linux/Unix systems like Ubuntu, the ~ character is a shell shorthand for your user's home directory—but Python's os.walk() doesn't automatically parse this symbol. When you pass '~/Downloads/pictures' directly to os.walk, it looks for a directory literally named ~ (which doesn't exist), so the loop never runs, leaving your folders list empty.
Windows handles path expansion differently (or your Windows environment might resolve ~ implicitly), which is why your original code works there.
The Fix: Expand the Path First
You just need to expand the ~ to its full absolute path before passing it to os.walk. Here's the corrected code:
import os # Expand ~ to the actual home directory path first path = os.path.expanduser('~/Downloads/pictures') folders = [] # r=root, d=directories, f = files for r, d, f in os.walk(path): for folder in d: folders.append(os.path.join(r, folder)) for z in folders: print(z)
This will convert ~/Downloads/pictures to something like /home/user/Downloads/pictures, which os.walk can properly traverse. You'll now get the expected paths in your folders list.
Bonus: More Efficient Approach for Direct Subdirectories
If you only need the immediate subdirectories (like folder1 and folder2, not nested subfolders inside them), you can skip os.walk entirely for a cleaner, faster solution:
import os path = os.path.expanduser('~/Downloads/pictures') # Use a list comprehension to grab only direct subdirectories folders = [ os.path.join(path, folder) for folder in os.listdir(path) if os.path.isdir(os.path.join(path, folder)) ] for z in folders: print(z)
This directly lists items in the target directory and filters for directories, which is more efficient if you don't need to traverse deeper.
内容的提问来源于stack exchange,提问作者Osama

