Python Forum
Python object that returns tuples? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python object that returns tuples? (/thread-2587.html)



Python object that returns tuples? - alfredocabrera - Mar-27-2017

I need to read a file and return it's data in a object. I have a Table class with a read() method :
class Table:
   def __init__(self,name='',fields=tuple(),tups=None):
   def read(fname):
This is my file (test.txt):
parts
pno,pname,color,weight,city
p1,Nut,Red,12,London
p2,Bolt,Green,17,Paris
p3,Screw,Blue,17,Rome
p4,Screw,Red,14,London
p5,Cam,Blue,12,Paris
p6,Cog,Red,19,London
If I call my "read()" method like this:
parts = Table.read(‘test.txt’)
print(parts)
I should get something like this:
Output:
parts('pno', 'pname', 'color', 'weight', 'city') ===== ('p1', 'Nut', 'Red', '12', 'London') ('p4', 'Screw', 'Red', '14', 'London') ('p6', 'Cog', 'Red', '19', 'London') ('p3', 'Screw', 'Blue', '17', 'Rome') ('p5', 'Cam', 'Blue', '12', 'Paris') ('p2', 'Bolt', 'Green', '17', 'Paris')
I'm new to python and any help would be appreciated. My biggest challenge is reading the file and saving it in the tuples :(
Moderator snippsat: Added code tag look at BBcode Help


RE: Python object that returns tuples? - Ofnuts - Mar-27-2017

See the CSV module...

import csv
with open('parts.dat') as csvfile:
    r=csv.reader(csvfile,delimiter=',')
    for line in r:
        print tuple(line)