繁体   English   中英

在 Python 中使用循环打开和操作一个文件夹中的几个.tiff 文件? 确保文件作为单独的变量导入

[英]Open and manipulate several .tiff files from one folder using a loop in Python? Ensuring the files are imported as separate variables

我有二十个.tif 文件,其中包含来自全局映射 model 的数据。我正在将文件导入 python,这样我就可以旋转它们,并使 .tif 文件以大西洋为中心而不是以太平洋为中心。 我可以使用下面的代码旋转单个文件,但是,我想导入所有 20 个文件,旋转它们,然后使用循环将它们全部保存在新位置,而不是为每个文件重复下面的代码行。

TLDR:我需要有关如何循环下面的代码的建议,以便可以轮换位于同一文件夹中的 20.tif 文件。

import rioxarray
rds_2000 = rioxarray.open_rasterio("path_to_tif")
rds_2000 = rds_2000.assign_coords(x=(((rds_2000.x + 180) % 360) - 180)).sortby('x')
rds_2000.rio.to_raster("path_to_newly_saved_tif)

在此处输入图像描述

也许是这样的?

假设您编写了一个 function 来捕获您附加的代码并返回处理后的文件

def process_function(filepath):
   do_something
   return processed_file

然后你可以创建一个dict或一个list ,如果你想通过文件名或其他一些方法访问文件 dict 可能更好。

files=os.listdir(files) #os some other method may be list comprehension
# alternative
# files=[file for file in os.listdir() if file.endswith(".tiff")
processed={}
for file in files:
   processed[file]=process_function(file)

现在您可以通过processed[<filename>]访问数据。

希望有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM