Search code examples
pythonfor-looplist-comprehensionstrippython-3.8

For-loop list comprehension with strip() function


This is my file:

test1,30 (# assuming \n is here)
test2,undefined (# assuming \n is here)
test3,5 valid attempts

This is my current code:

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

How do I make it such that if I do print(openFinalFile["test1"]), it'll return the value which is 30 (shown in file)?

Error returned: builtins.ValueError: too many values to unpack (expected 2)


Solution

  • I would rather user 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"])