使用 strip() 函数的 For 循环列表理解
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"])
如果我打印(openFinalFile["test1"]),我如何做到这一点,它会return 30 的值(在文件中显示)?
错误 returned: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"])
这是我的文件:
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"]),我如何做到这一点,它会return 30 的值(在文件中显示)?
错误 returned: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"])