我正在尝试编写一个Python代码,通过调整此代码将LANDSAT卫星图像导入Grass GIS:http://grass.osgeo.org/wiki/LANDSAT
LANDSAT磁贴下载为文件夹,每个文件夹包含7个tiff图像(1-7频段)。因此,我有一个目录,其中包含几个子目录(每个LANDSAT磁贴一个)。
我目前的代码如下:
#!/usr/bin/python
import os
import sys
import glob
import grass.script as grass
def import_tifs(dirpath):
for dirpath, dirname, filenames in os.walk(dirpath):
for dirname in dirpath:
dirname = os.path.join(dirpath,dirname)
for file in os.listdir(dirname):
if os.path.splitext(file)[-1] != '.TIF':
continue
ffile = os.path.join(dirname, file)
name = os.path.splitext(file)[0].split(dirname)[-1]
grass.message('Importing %s -> %s@%s...' % (file, name, dirpath))
grass.run_command('r.in.gdal',
flags = 'o',
input = ffile,
output = name,
quiet = True,
overwrite = True)
def main():
if len(sys.argv) == 1:
for directory in filter(os.path.isdir, os.listdir(os.getcwd())):
import_tifs(directory)
else:
import_tifs(sys.argv[1])
if __name__ == "__main__":
main()
我收到以下错误:
Traceback (most recent call last):
File "C:/Users/Simon/Documents/import_landsat2.py", line
40, in <module>
main()
File "C:/Users/Simon/Documents/import_landsat2.py", line
37, in main
import_tifs(sys.argv[1])
File "C:/Users/Simon/Documents/import_landsat2.py", line
17, in import_tifs
for file in os.listdir(dirname):
WindowsError: [Error 3] The system cannot find the path
specified: 'dirpath\\C/*.*'
任何人都可以解释发生了什么以及我需要做些什么来解决它,或建议替代方案?感谢。
答案 0 :(得分:2)
我认为你的主要问题是dirname
中的os.walk()
会返回一个列表(不是字符串),因此你的后续字符串(即dirname = os.path.join(dirpath,dirname)
)有点格式错误。这是一个可能的替代方案 - 为了测试这个,我使用目录的完整路径sys.argv[1]
,但你可以使它更具动态以适应你的情况。另外,请避免使用file
等变量名,因为它们是Python关键字。我无法测试您的grass.*
功能,但希望这将是一个足够清晰的示例,以便您可以调整您的需求。 os.walk()
本地处理大量标准解析,因此您可以删除一些目录操作函数:
def import_tifs(dirpath):
for dirpath, dirname, filenames in os.walk(dirpath):
# Iterate through the files in the current dir returned by walk()
for tif_file in filenames:
# If the suffix is '.TIF', process
if tif_file.upper().endswith('.tif'):
# This will contain the full path to your file
full_path = os.path.join(dirpath, tif_file)
# tif_file will already contain the name, so you can call from here
grass.message('Importing %s -> %s@%s...' % (full_path, tif_file, dirpath))
grass.run_command('r.in.gdal',
flags = 'o',
input = full_path,
output = tif_file,
quiet = True,
overwrite = True)
答案 1 :(得分:2)
我刚刚重写了你的代码以列出所有目录树并找到文件扩展名,在本例中为“.tif”,
#!/usr/bin/python
import os
import sys
def import_tifs(dirpath):
for dirpath, dirname, filenames in os.walk(dirpath):
for filename in filenames:
name, extension = os.path.splitext(filename)
if extension.lower() == ".tif":
filepath = os.path.join(dirpath, filename)
print(filepath, name, dirpath)
def main():
if len(sys.argv) == 1:
import_tifs(os.getcwd())
else:
import_tifs(sys.argv[1])
if __name__ == "__main__":
main()
请检查您是否正在寻找...