繁体   English   中英

使用 strip() 的 for 循环列表理解 function

[英]For-loop list comprehension with strip() function

这是我的文件:

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

我如何做到这一点,如果我执行 print(openFinalFile["test1"]),它将返回 30 的值(显示在文件中)?

返回错误:builtins.ValueError:解压的值太多(预期为 2)

我宁愿用户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"])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM