1

I am trying to open/read a text file with multiple "sets" of values, some lists, some integers.

I am struggling to figure out what the best course of action to do this would be.

I have provided an example of the text file I am attempting to import and manipulate below. Basically, each line of the text file holds 6 values, and all these values relate to one another. My end goal is to be able to have almost a "list of list" set up so that I can define each set of six values almost as one.

Does anyone have any thoughts on this?

house, brick, 876, no, yes, 3
apartment, wood, 345, yes, yes, 1
condominium, brick, 453, no, yes, 8
etc... 

My intended end point is to be able to categorize each variable (for example, building type == house, material == brick, etc. and be able to search through these.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    By *importing* you mean *opening*? You can only import `.py` files. And, have you tried anything at all? Any piece of code we can help with? – Tomerikoo Jul 17 '19 at 23:31
  • `import`ing has a special, specific [meaning](https://docs.python.org/3/reference/simple_stmts.html#the-import-statement) in Python that has to do with using code in other libraries/modules, not reading data — and that _doesn't_ sound like what you're asking about. – martineau Jul 17 '19 at 23:59

1 Answers1

0

So just try to open your file and then you need to split on the newline aswell as on the commas in your text. This will give you the "list of lists" you wanted. Furthermore I would suggest you to remap everything in a dict so you can access your items by a useful key.

Could be something like this:

with open('test.txt', 'r') as f:
    data = f.read()

    data = data.split("\n")
    list_of_lists = [row.split(",") for row in data]
    final_list = [{"building_type": row[0].strip(),
                   "material": row[1].strip(),
                   "your_keys": row[2].strip()} for row in list_of_lists]
    print(final_list)

Output:

[{'building_type': 'house', 'material': 'brick', 'your_keys': '876'},
 {'building_type': 'apartment', 'material': 'wood', 'your_keys': '345'}, 
 {'building_type': 'condominium', 'material': 'brick', 'your_keys': '453'}]
Steven
  • 170
  • 3
  • 10
  • 2
    To save some space in memory it would be a good idea to loop over the file instead of reading it all at once – Tomerikoo Jul 17 '19 at 23:46