don don - 2 months ago 6
Python Question

Python: Create a Map (tuple) from a text file

I am new to python and I have learned a lot by taking tough problems. I need the communities help to solve this one. I have a text file with the following data.

river,4
-500, -360
-500, 360
500, 360
500,-360

sand, 3
400, 300
500, 300
200, 100


My question is I need to take this file load it and create a
tuple
that looks like the following:

block=("river",4,(-500, -360),(-500, 360),(500, 360),(500,-360)), ("sand", 3,(400,300), (500, 300), (200, 100))


This is my code so far

file=open("file.txt", "r")
lineString=file.readlines()


Please don't downvote me for no reason. I new to the community and learning python.

Answer

This will give you what you want:

import csv

output = []
block = ()
with open('input_file') as in_file:
    csv_reader = csv.reader(in_file)
    for row in csv_reader:
        output.append(tuple(row))

first_element = output[0]
a, b, c, d = output[1:]
block = (first_element[0], a, b, c, d)

prints

("river",(-500, -360),(-500, 360),(500, 360),(500,-360))

I must say your way of organizing the data makes no sense to me. The above code will work only when there are 4 lines after river, 4 line. If there are more replace:

a, b, c, d = output[1:]
block = (first_element[0], a, b, c, d)

with

block = (first_element[0], output[1:])

But in this case the output will be:

("river",[(-500, -360),(-500, 360),(500, 360),(500,-360)])