Reputation: 13
So, i have this text file which contains this info:
rect 20 20 80 50 True
tri 80 50 20 35 False
What i want to do is write a function to read the type and coordinates of a shape from the text file and return the results in the form of a list:
readShapes('test.txt')
[{'kind': 'rect', 'bounds': [20, 20, 80, 50], 'fill': True}, {'kind': 'tri', 'bounds': [80, 50, 20, 35], 'fill': False}]
What i tried is this (granted it's inefficient but I'm just trying to be deliberate in my coding process for now):
# reads a file and returns a corresponding list of shapes
def readShapes(filename):
my_file = open(filename, 'r')
lines = my_file.readlines()
fieldnames = ["kindVal", "x0", "y0", "x1", "y1", "fillVal"]
results = []
for line in my_file:
dictionary = {}
fields = line.split(" ")
for i in range(6):
kindVal = str(fieldnames[0])
x0 = int(fieldnames[1])
y0 = int(fieldnames[2])
x1 = int(fieldnames[3])
y1 = int(fieldnames[4])
fillVal = str(fieldnames[5])
shape = {'kind': kindVal, 'bounds': [x0, y0, x1, y1], 'fill': fillVal}
results.append(dictionary)
print(results)
return results
Upvotes: 1
Views: 671
Reputation: 61910
You could use extended iterable unpacking:
res = []
with open('data.txt') as infile:
for line in infile:
kind, *bounds, fill = line.split()
res.append({'kind': kind, 'bounds': bounds, 'fill': fill})
print(res)
Output
[{'kind': 'rect', 'bounds': ['20', '20', '80', '50'], 'fill': 'True'}, {'kind': 'tri', 'bounds': ['80', '50', '20', '35'], 'fill': 'False'}]
If the fill key needs to be a boolean, you could do instead:
res.append({'kind': kind, 'bounds': bounds, 'fill': bool(fill == 'True')})
Or perhaps, more secure:
# from ast import literal_eval
res.append({'kind': kind, 'bounds': bounds, 'fill': literal_eval(fill)})
Upvotes: 9