首页 > 解决方案 > 在Python中的变量中传递列表的每个部分?

问题描述

我有这段代码,在其中搜索包含特定文件扩展名的子文件夹的主文件夹并在 Python 中打开它。

rootdir = '/path/to/dir' # path to your root directory you walk
sfiles = [] # a list with all the .shp files
for entry in os.listdir(rootdir):
    dirpath = os.path.join(rootdir, entry)
    if os.path.isdir(dirpath): 
        for file in os.listdir(dirpath): # Get all files in the subdirectories
            if file.endswith('.shp'): # If it's an .shp.
                filepath = os.path.join(dirpath, file)
                sfiles.append(filepath)
                fiona.open(filepath)

现在尝试分配它

a=sfiles[0]
a.schema #method 
AttributeError: 'str' object has no attribute 'schema'

标签: pythonimmutability

解决方案


如果你想调用一个方法,你需要像这样使用括号:

a.schema()

您收到的错误消息是正确的:

AttributeError: 'str' object has no attribute 'schema'

您附加到sfile的内容只是字符串,并且字符串不包含名为“模式”的属性或具有此名称的方法。

也许您想添加文件句柄而不是路径?

sfiles.append(fiona.open(filepath))

再说一次,一次打开这么多文件并不是一个好主意。也许像现在一样找到文件并在以后的循环中一次打开一个文件?


推荐阅读