Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用strip()函数进行循环列表理解_Python_For Loop_List Comprehension_Strip_Python 3.8 - Fatal编程技术网

Python 使用strip()函数进行循环列表理解

Python 使用strip()函数进行循环列表理解,python,for-loop,list-comprehension,strip,python-3.8,Python,For Loop,List Comprehension,Strip,Python 3.8,这是我的档案: test1,30 (# assuming \n is here) test2,undefined (# assuming \n is here) test3,5 valid attempts 这是我当前的代码: ## <> arrows suggests input & not shown here import os os.system(<file path directory>) with open(<file path direc

这是我的档案:

test1,30 (# assuming \n is here)
test2,undefined (# assuming \n is here)
test3,5 valid attempts
这是我当前的代码:

## <> arrows suggests input & not shown here

import os

os.system(<file path directory>)
with open(<file path directory>) as openDocument:
    openfile = openDocument.read()
    openfile = openfile .replace("\x00", "").split("\n")   
    openfile = [openfile .split(",") for openfile in openfile [1:]]
    openFinalFile = {policyName.strip(): policyValue.strip() for policyName, policyValue in openFile if policyName != ''} ## Currently causing an error

    print(openFinalFile["test1"])

我如何使它,如果我做了printopenFinalFile[test1],它将返回文件中显示的值30

返回的错误:builtins.ValueError:太多的值无法解压缩预期的2

我希望用户pathlib:


在代码中,当前有一条注释导致错误。您可以编辑问题并将错误放在那里吗?当您使用:对于policyName,openFinalFile中的policyValue时,openFinalFile尚未定义。你期待那里会发生什么?欢迎来到SO!看看这本书。对于调试问题,您需要提供,但尚未提供错误消息。另外,我认为您对某些事情感到困惑,因为目录是不可执行的,并且不能像文件一样打开,至少在Linux上不是这样-不确定其他操作系统。即使目录是一个打字错误,它仍然没有多大意义。因此,您需要提供完整的代码-尖括号中没有任何内容。还要看看你是否需要更多的建议。我已经更新了代码并把错误放在那里。谢谢!我会试一试,然后很快给你回复:
from pathlib import Path
lines = Path(<file path directory>).read_text().replace("\x00", "").splitlines()
pairs = [i.split(',') for i in lines]
openFinalFile = {k.strip(): v.strip() for k, v in pairs if k}
print(openFinalFile["test1"])