如何在R中通过*MTL.txt模式读取LANDSAT影像元数据文件
Absolutely! You can avoid hardcoding the exact MTL filename by using pattern matching to automatically locate the correct file in your target directory. Here's a clean, robust way to do this in R:
First, set your working directory as before, then use list.files() with a precise regex pattern to target LANDSAT's MTL files (which consistently end with _MTL.txt):
# Set working directory to your LANDSAT folder setwd("C:/Users/Documents/L5__002072-09MAY-2006") # Find all files matching the MTL file pattern mtl_files <- list.files(pattern = "_MTL\\.txt$") # Validate and read the file if (length(mtl_files) == 1) { mtl <- read.delim(file = mtl_files[1], sep = '=', stringsAsFactors = FALSE) print(mtl) } else if (length(mtl_files) > 1) { warning("Multiple MTL files found in the directory! Please check for duplicates.") } else { stop("No MTL files detected in the specified folder.") }
Pattern Breakdown
The regex _MTL\\.txt$ ensures we only match valid MTL files:
_MTL: Matches the literal string "_MTL" specific to LANDSAT metadata files\\.: Escapes the dot (since dots in regex match any character, we need this to target an actual file extension dot)txt$: Anchors the pattern to the end of the filename, ensuring we only pick files that end with "txt"
Simplified Version (For Single File Scenarios)
If you’re 100% certain there’s exactly one MTL file in the folder, you can shorten the code to:
mtl <- read.delim(file = list.files(pattern = "_MTL\\.txt$"), sep = '=', stringsAsFactors = FALSE)
Adding the file count check is still a good practice, though—it helps catch errors like missing files or accidental duplicates early, which is invaluable if you plan to batch-process multiple LANDSAT folders.
内容的提问来源于stack exchange,提问作者Cotimaass

