You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu 16.04下os.walk获取子目录为空问题求助

Fixing Empty 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:58:31