Python Forum
Python object that returns tuples?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python object that returns tuples?
#1
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
Reply
#2
See the CSV module...

import csv
with open('parts.dat') as csvfile:
    r=csv.reader(csvfile,delimiter=',')
    for line in r:
        print tuple(line)
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python update binary object (override delivered Object properties) pierre38 4 1,773 May-19-2022, 07:52 AM
Last Post: pierre38
  Annualised returns in python. Urgent request shivamdang 2 2,176 Apr-12-2020, 07:37 AM
Last Post: shivamdang
  Python function returns inconsistent results bluethundr 4 3,199 Dec-21-2019, 02:11 AM
Last Post: stullis
  class returns NoneType Object istemihan 0 2,259 Aug-12-2019, 11:47 AM
Last Post: istemihan
  Python returns generator instead of None Tawnwen 4 4,707 Mar-09-2018, 07:06 AM
Last Post: DeaD_EyE
  want to know the kind of object whether its a python or json object johnkennykumar 5 62,102 Jan-21-2017, 08:47 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020