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

无法获取文件夹文件名求助:!ls表达式报错

问题分析:获取文件夹文件名异常的原因及解决办法

问题场景

你运行以下Python代码尝试获取指定文件夹内的文件名:

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

#Ruta raiz
PATH="/content/drive/MyDrive/Flores"

#Datos de entrada
INPATH="/content/drive/MyDrive/Flores/processed"

#Datos de salida
OUTPATH=PATH+'/test/'

# Ruta de checkpoints
CKPATH=PATH+'/checkpoints'

imgurls = !ls -1 "{INPATH}"

imgurls

出现两个异常:

  • 输出结果仅为['JPEG'],但该路径下实际应有924个文件
  • 同时抛出“Expected expression on "!ls" expression”错误

原因解析

  1. !ls语法错误的原因:!ls是Jupyter Notebook(含Colab)专属的魔法命令,只有在Jupyter类环境中才能直接执行。如果是在普通Python脚本或非Jupyter IDE(如PyCharm)中运行,Python会将!判定为非法语法,从而触发错误。

  2. 输出仅为['JPEG']的原因:这说明你指定的INPATH路径下,并没有直接存放那924个文件,而是存在一个名为JPEG的子文件夹,你要找的924个文件实际存储在/content/drive/MyDrive/Flores/processed/JPEG这个子目录里。

解决办法

方法1:Jupyter环境下修正使用

如果是在Colab或Jupyter Notebook中运行,先修正目标路径,再使用魔法命令:

INPATH="/content/drive/MyDrive/Flores/processed/JPEG"
imgurls = !ls -1 "{INPATH}"

方法2:通用Python写法(跨环境兼容,推荐)

使用Python标准库的os或pathlib模块获取文件名,无需依赖Jupyter环境:

用os模块实现

import os

# 修正为实际存储文件的路径
target_path = "/content/drive/MyDrive/Flores/processed/JPEG"
# 获取目录下所有文件名
imgurls = os.listdir(target_path)
# 若需要完整文件路径,改用此写法
# imgurls = [os.path.join(target_path, filename) for filename in os.listdir(target_path)]

用pathlib模块实现(Python3.4+)

from pathlib import Path

target_path = Path("/content/drive/MyDrive/Flores/processed/JPEG")
# 获取目录下所有文件的名称(排除子文件夹)
imgurls = [file.name for file in target_path.iterdir() if file.is_file()]
# 若需要完整文件路径,改用此写法
# imgurls = [str(file) for file in target_path.iterdir() if file.is_file()]

内容的提问来源于stack exchange,提问作者Federico

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:41:32