0

I'm trying to read below text file in python, I'm struggling to get as key value in output but its not working as expected:

test.txt

productId1 ProdName1,ProdPrice1,ProdDescription1,ProdDate1
productId2 ProdName2,ProdPrice2,ProdDescription2,ProdDate2
productId3 ProdName3,ProdPrice3,ProdDescription3,ProdDate3
productId4 ProdName4,ProdPrice4,ProdDescription4,ProdDate4

myPython.py

import sys
with open('test.txt') as f
  lines = list(line.split(' ',1) for line in f)
  for k,v in lines.items();
     print("Key : {0}, Value: {1}".format(k,v))

I'm trying to parse the text file and trying to print key and value separately. Looks like I'm doing something wrong here. Need some help to fix this?

Thanks!

3
  • 2
    What do you expect? What happens? Commented Nov 5, 2017 at 23:33
  • You have a syntax error at line 2 here Commented Nov 5, 2017 at 23:37
  • 1
    Why do you expect your lines list to have an items method??? list objects don't have "keys" and "values", that's for mappings, i.e. dict objects. Commented Nov 5, 2017 at 23:39

6 Answers 6

3

You're needlessly storing a list.

Loop, split and print

with open('test.txt') as f:
    for line in f:
        k, v = line.rstrip().split(' ',1) 
        print("Key : {0}, Value: {1}".format(k,v))
Sign up to request clarification or add additional context in comments.

4 Comments

@alfasin Same thing
Why I'm getting blank line after each key and value - which is breaking my other logic
@cricket_007 same thing with the OP's example true, but won't work on samples that have more than one space and I like explicit better than implicit. Please excuse my pettiness...
@rubydeveloper Each line ends in a \n, a newline. Without the rstrip() , the newline is preserved. I assume that is causing an empty line somehere.
0

This should work, with a list comprehension:

with open('test.txt') as f:
    lines = [line.split(' ',1) for line in f]
    for k, v in lines:
        print("Key: {0}, Value: {1}".format(k, v))

Comments

0

You can make a dict right of the bat with a dict comp and than iterate the list to print as you wanted. What you had done was create a list, which does not have an items() method.

with open('notepad.txt') as f:
    d = {line.split(' ')[0]:line.split(' ')[1] for line in f}
    for k,v in d.items():
        print("Key : {0}, Value: {1}".format(k,v))

9 Comments

Why call line.split() twice?
i don't know how else to do it, since i need to split the key and the value. how do you recommend doing otherwise?
Yes. Exactly. Don't do something silly just to cram something in a comprehension.
Split once on the line before
But more generally, the point I wanted to make was that there's nothing wrong with a for-loop. comprehension constructs give you marginal improvements in speed, their main advantage is clarity/elegance. So if you find yourself violating the DRY principle, it's a big signal that you should just use a for-loop :)
|
0

lines is a list of lists, so the good way to finish the job is:

import sys
with open('test.txt') as f:
  lines = list(line.split(' ',1) for line in f)
for k,v in lines:
   print("Key : {0}, Value: {1}".format(k,v))

Comments

0

Perhaps I am reading too much into your description but I see one key, a space and a comma limited name of other fields. If I interpret that as their being data for those items that is comma limited then I would conclude you want a dictionary of dictionaries. That would lead to code like:

data_keys = 'ProdName', 'ProdPrice', 'ProdDescription', 'ProdDate'
with open('test.txt') as f:
  for line in f:
    id, values = l.strip().split()  # automatically on white space
    keyed_values = zip(data_keys, values.split(','))
    print(dict([('key', id)] + keyed_values))

Comments

-1

You can use the f.readlines() function that returns a list of lines in the file f. I changed the code to include f.lines in line 3.

import sys
with open('test.txt') as f:
  lines = list(line.split(' ',1) for line in f.readlines())
  for k,v in lines.items();
     print("Key : {0}, Value: {1}".format(k,v))

1 Comment

there is no .lines method, and anyway, you can iterate over the file-handler directly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.