在Python中用一个变量传递列表的每一部分?

2024-09-24 22:26:31 发布

您现在位置: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'

Tags: thetopathin文件夹forosfiles
2条回答

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

a.schema()

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

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

附加到sfiles的东西只是字符串,字符串不包含名为“schema”的属性或具有此名称的方法

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

sfiles.append(fiona.open(filepath))

再说一遍,一次打开这么多文件不是个好主意。 也许找到文件,因为你现在正在做的和打开一个文件在一次以后的循环

filesList = list()
extension = "*.shp"
rootdir = '/path/to/dir'

for path, subdirs, files in os.walk(rootdir):
     for name in files:
        if fnmatch(name, extension):
             #filesList.append(os.path.join(path, name)) 
             with open(os.path.join(path, name), 'r') as fp:
                   #write your own logic here.

如果要在列表中追加,并且要在后续代码中使用相同的内容,请使用:

filesList.append(os.path.join(path, name))

否则您可以直接使用:

with open(os.path.join(path, name), 'r') as fp:

尝试:

a=sfiles[0]
a.schema()

#schema是一种方法,它可能是您因漏掉“()”而出错的原因

相关问题 更多 >