使用rasterio.open()时文件可打印却无法打开的问题
问题原因
你遇到的问题核心是文件路径不完整:
os.listdir(refPath)返回的仅仅是目标目录下的文件名(比如2014_NDWI.tif),而非完整的文件路径- 当你调用
rs.open(file)时,程序会在当前工作目录下查找这个文件,而不是你指定的/Users/admin/Downloads/Landsat8/目录,所以会提示文件不存在
解决方案
最稳妥的方式是用os.path.join()将目录路径和文件名拼接成完整路径,修改后的代码如下:
import os import rasterio as rs refPath = '/Users/admin/Downloads/Landsat8/' ext = '_NDWI.tif' for file in sorted(os.listdir(refPath)): if file.endswith(ext): print(file) # 拼接完整文件路径 full_file_path = os.path.join(refPath, file) ndwiopen = rs.open(full_file_path) ndwiread = ndwiopen.read(1)
另外也可以先切换工作目录到目标路径(不推荐,可能影响后续其他文件操作):
import os import rasterio as rs refPath = '/Users/admin/Downloads/Landsat8/' ext = '_NDWI.tif' # 切换到目标目录 os.chdir(refPath) for file in sorted(os.listdir(refPath)): if file.endswith(ext): print(file) ndwiopen = rs.open(file) ndwiread = ndwiopen.read(1)
补充说明
- 优先使用第一种方法,因为它不会改变当前工作目录,避免后续文件操作出现路径混乱
- 确保你已经导入了
os模块,否则代码会报错
内容的提问来源于stack exchange,提问作者Arnab paul
相关产品推荐
相关产品推荐

