带strip()函数的Forloop列表理解

2024-09-27 07:35:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的档案:

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"])

如何使打印(openFinalFile[“test1”])时返回的值为30(如文件所示)

返回的错误:builtins.ValueError:要解压缩的值太多(应为2个)


Tags: pathinforhereisosdirectoryfile
1条回答
网友
1楼 · 发布于 2024-09-27 07:35:17

我宁愿用户pathlib

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"])

相关问题 更多 >

    热门问题