【问题标题】:TypeError: unhashable type: 'list' Python error while appendTypeError: unhashable type: 'list' Python error while append
【发布时间】:2021-07-08 08:36:02
【问题描述】:

我有一个包含测试用例排序的 CSV 文件,我有一个无序的 xml 文件,我正在尝试根据 csv 文件对 xml 文件进行排序。这样做时我收到此错误:-

TypeError                                 Traceback (most recent call last)
<ipython-input-208-7ef10cfb792b> in <module>
     28     for TestCaseName in csv_order:
     29         try:
---> 30             children.append(tests.pop(TestCaseName))
     31         except KeyError:
     32             print(f"Test '{TestCaseName}' not present")

TypeError: unhashable type: 'list'

这是我的代码:-

from bs4 import BeautifulSoup
import csv

# Read in the XML and parse it

with open(r'example_xml/DM12_new.xml') as f_input:
    soup = BeautifulSoup(f_input, 'xml')

# Store all test tags in a dictionary

tests = {}

for test in soup.find_all('Test'):
    tests[test['Name']] = test

# Locate the children tag and empty it

children = soup.find('Children')
children.clear()

# Read in the ordering CSV and append the tests in the required order into
# the children tag

with open(r'csv/SPT.csv', newline='') as f_order:
    csv_order = csv.reader(f_order)
    header = next(csv_order)

    for TestCaseName in csv_order:
        try:
            children.append(tests.pop(TestCaseName))
        except KeyError:
            print(f"Test '{TestCaseName}' not present")

# Add any remaining tests not listed in the CSV

for test in tests.values():
    children.append(test)

# Write the modified XML

with open(r'example_xml/output.xml', 'w') as f_output:
    f_output.write(str(soup))

这里有什么问题,有人可以帮我解决吗?提前致谢

【问题讨论】:

    标签: python xml csv typeerror csvreader


    【解决方案1】:

    这里

    with open(r'csv/SPT.csv', newline='') as f_order:
        csv_order = csv.reader(f_order)
        header = next(csv_order)
    
        for TestCaseName in csv_order:
            try:
                children.append(tests.pop(TestCaseName))
            except KeyError:
                print(f"Test '{TestCaseName}' not present")
    

    TestCaseName 保存 csv 文件给定行的所有值,这是您的意图还是应该是其中一列的值,例如第一列的 TestCaseName[0]

    【讨论】:

    • TestCaseName 保存所有值
    • 这不是答案,而是评论。
    • @StackLifeOfMe 那么tests 的键是否对应于文件的整行?
    • 我在 csv 中有多个列,例如 Id、TestCaseName、Processing_time 等。我要做的是根据包含测试用例名称的 TestCaseName 列,我想使用该列对XML 文件。 Xml 文件也包含相同的名称,但以无序的方式。
    • @StackLifeOfMe 那么你可能应该先获取正确的列,如果 TestCaseName 是第二列替换 children.append(tests.pop(TestCaseName)) 使用 children.append(tests.pop(TestCaseName[1]))
    猜你喜欢
    • 2015-02-11
    • 2020-05-11
    • 2022-12-05
    • 2021-03-14
    • 1970-01-01
    • 2019-10-11
    • 2020-03-27
    • 1970-01-01
    • 2018-06-04
    相关资源
    最近更新 更多