【问题标题】:Error: No such file or directory. Unable to write files within for loop in python错误:没有这样的文件或目录。无法在python的for循环中写入文件
【发布时间】:2022-01-05 21:15:45
【问题描述】:

我正在尝试使用 python 中的 rasterio 包将光栅图像划分为 for 循环的一部分(光栅图像就像地理空间分析世界中的矩阵/像素数组),但是我无法弄清楚目录问题.我实际上是在尝试遍历文件夹中的文件,然后将每个文件除以目标文件,然后生成唯一的输出产品文件。

我有以下代码:

#I am just interested in files containing these strings
d = ['Blue', 'Red', 'Green']
test = 'Colors/test_value.tif'
folder = Path('Colors')

src = rasterio.open(test) 

#Loop through all the '.tif' files in the folder, but only those that contain 'Blue, Red, or Green in the file name
for f in folder.glob("*.tif"):
    if any(color in f.name for color in d):

        med = rasterio.open(f) 
        new_raster = med.read(1)/src.read(1)

        # write raster
        profile = src.profile
        profile.update(
            dtype=new_raster.dtype,
            count=1,
            compress='lzw')
        #Create the output files with each unique file name
        with rasterio.open(f"Colors/Output_Raster_{f}.tif", 'w', **profile) as dst:
            dst.write(new_raster, 1)

所以我在引用的“文件夹”中有 4 个感兴趣的文件。它们是:Raster_Blue.tifRaster_Red.tifRaster_Green.tifRaster_test.tif。我想遍历文件夹并将每个文件除以“Raster_test.tif”。但是,我只想将蓝色、红色和绿色文件用于我的操作,因此我不想运行“Raster_test.tif”除以“Raster_test.tif”。

因此,这段代码试图遍历文件夹中文件名字符串中包含“蓝色”、“红色”和“绿色”的文件,并且对于每次迭代,将特定颜色文件除以 @987654326 @。然后我想写那些输出文件。挑战在于,对于这些输出文件中的每一个,总共三个,对于循环将经历的三个迭代,我想给它们每个一个唯一的文件名,所以文件不只是每次都被覆盖。所以我想产生Output_Raster_Blue.tifOutput_Raster_Red.tifOutput_Raster_Green.tif。但是,当我尝试此代码时,我收到此错误消息:RasterioIOError: Attempt to create new tiff file 'Colors/Output_Raster_Colors\Output_Raster_Red.tif.tif' failed: No such file or directory

我的目标目录和文件名字符串似乎有点混乱,我无法弄清楚如何解决这个问题,或者为什么会发生这种情况。如何修复循环以便引用正确的目录?

【问题讨论】:

    标签: python directory raster write rasterio


    【解决方案1】:

    似乎f变量在rasterio.open(f"Colors/Output_Raster_{f}.tif", 'w', **profile)这一行被转换为字符串。

    所以"Colors/Output_Raster_{f}.tif" 变成了"Colors/Output_Raster_Colors\Output_Raster_Red.tif.tif",如您所见,创建了一个新的错误路径,open 函数无法在不存在的目录中创建文件。

    我认为将f 更正为f.name 就可以了。

    【讨论】:

    • 解决了!是的,我将该代码行从 with rasterio.open(f"Colors/Output_Raster_{f}.tif", 'w', **profile) as dst: 更改为 with rasterio.open(f"Colors/Output_Raster_{f.name}.tif", 'w', **profile) as dst: 并且它有效!谢谢!
    猜你喜欢
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    相关资源
    最近更新 更多