Bogota
Bogota

Reputation: 391

Python Split function for Values in Text File

I have a input file Input.txt and in the input I have content as

Name1=Value1
Name2=Value2
Name3=Value3

Now from the input file, I'm able to split the values as per new line. Next task is to store the name and value pairs in Dictionary. I tried by the following method,

with open("Input.txt", "r") as param_file:
    for line in param_file:
        str = line.split()
        d = dict(x.split("=") for x in str.split("\n"))

        for k,v in d.items():
            print(k, v)

but this is giving me error as: AttributeError: 'list' object has no attribute 'split' I know that the list does not have split function that's why I'm getting this. What could be the correct way to implement this?

Expected output is:

Name1 Value1
Name2 Value2
Name3 Value3

Upvotes: 2

Views: 1230

Answers (4)

Ghasem
Ghasem

Reputation: 15573

You dont have to split with \n as each line is one of the lines in the file. Just split the line based on = and get the first and second elements.

with open("Input.txt", "r") as param_file:
    for line in param_file:
        strip_line = line.rstrip().split("=")
        d = {strip_line[0]: strip_line[1]}

        for k,v in d.items():
            print(k, v)

Upvotes: 1

Jan
Jan

Reputation: 43169

This will yield a list of dicts:

data = """
Name1=Value1
Name2=Value2
Name3=Value3
"""

result = [{key: value} 
          for line in data.split("\n") if line 
          for key, value in [line.rstrip().split("=")]]
print(result)
# [{'Name1': 'Value1'}, {'Name2': 'Value2'}, {'Name3': 'Value3'}]


Or - I believe this is more what you're after:

result = {key: value
          for line in data.split("\n") if line
          for key, value in [line.split("=")]}
# {'Name1': 'Value1', 'Name2': 'Value2', 'Name3': 'Value3'}

Upvotes: 0

Błotosmętek
Błotosmętek

Reputation: 12927

I believe what you really want is this:

with open("Input.txt", "r") as param_file:
    d = dict(line.rstrip().split("=") for line in param_file )

for k,v in d.items():
    print(k, v)

Upvotes: 0

Samay Gupta
Samay Gupta

Reputation: 437

There are a couple of issues that rise up. first is the dictionary you're creating gets overridden on every iteration. This essentially means that the dict d will store only the value of the last line. One option is to read the entire file with .readlines() and remove the for loop. It should look something like :

with open("Input.txt", "r") as param_file:
    text = param_file.readlines()
    d = dict(x.strip().split("=") for x in text)
    for k,v in d.items():
        print(k, v)

Upvotes: 2

Related Questions