with path.open('r', encoding="utf-8") as file: AttributeError: 'generator' object has no attribute 'open'

with path.open('r', encoding="utf-8") as file: AttributeError: 'generator' object has no attribute 'open'

我不太确定如何访问文件名并按照脚本中的说明进行必要的更改?我正在尝试访问文件夹内的一些文件。 我还想使用这些文件,如第

行所示

item = etree.Element('language', attrib={"lang": path.parent.name, "status": "Reviewed"})

import pathlib
import functools
import operator
import lxml.etree as etree
from lxml.builder import ElementMaker

ATTRIB = {"xsi": "test.xsd", "xmlns": "http://www.w3.org/2001/XMLSchema-instance"}



def is_element(node):
    return hasattr(node, 'attrib') and 'name' in node.attrib


def create_plural(item):
    pass



def main():
    cwd = pathlib.Path.cwd()
    directories = list(filter(lambda path: path.is_dir(), cwd.iterdir()))
    langs = [path.name for path in directories]
    files = map(operator.methodcaller('glob', '*.xml'), directories)
    #trees = dict.fromkeys(unique_names, dict())


    for path in files:
        with path.open('r', encoding="utf-8") as file:
            tree = etree.parse(file)
        root = tree.getroot()
        name = xml_path.with_suffix('').with_suffix('').name
        out_tree = trees[name]



        for child in filter(is_element, root):
            id = child.attrib['name']
            text = child.text
            if id not in out_tree:
                out_tree[id] = list()
            item = etree.Element('language', attrib={"lang": path.parent.name, "status": "Reviewed"})
            if child.tag == "plurals":
                item.text = create_plural(child)
            else:
                item.text = etree.CDATA(text)
            out_tree[id].append(item)



if __name__ == '__main__':
    main()



    #name = '{}.strings.xml'.format(xml_file.with_suffix('').name)  # name of the file
        #out_p = out_path / lang / name  # path of the output file where it should be located
        #out_p.parent.resolve().mkdir(parents=True, exist_ok=True)  # make directory
        #text = etree.tostring(root, xml_declaration=True, pretty_print=True, encoding="utf-8")
        #with out_p.open('wb') as file:
        #    file.write(text) ```



而不是:

with path.open('r', encoding="utf-8") as file:
    tree = etree.parse(file)

您可以直接传递一个文件名(字符串)来解析:

tree = etree.parse(path)

path 在您的示例中是一个字符串,因此它没有 open 函数。

也许你的意思是:

with open(path, 'r', encoding="utf-8") as file:
    tree = etree.parse(file)

如果您试图在当前目录中查找 xml 个文件名:

[f for f in os.listdir('.') if f.endswith('.xml')]

问题是这样的:

files = map(operator.methodcaller('glob', '*.xml'), directories)

glob returns 路径生成器,因此 file 不是路径序列而是路径序列的序列。

您需要将整个内容 itertools.chain.from_iterable 成一个序列,或者使用嵌套循环。或者使用理解来直接打开整个东西。 map 当你已经有一个函数可以做你需要的事情时很有意义,但这里不是这种情况,所以理解往往是可取的:

files = (
    f
    for d in directories
    for f in d.glob('*.xml')
)