Python - import file into NamedTuple

I recently had a question about data types.
Since then I have been trying to use NamedTuples (with more or less success).

My problem now:
- How to import lines from a file into new tuples,
- How to import values ​​separated by a space / tab (/ all) into a given part of a tuple?

Like:

Monday  8:00    10:00   ETR_28135   lh1n1522    Computer science    1     
Tuesday 12:00   14:00   ETR_28134   lh1n1544    Geography EA    1  

The first line should go into the tuple [0]. The first data: tuple [0] .day; second: tuple [0] .start; .. and so on.
And when a new line begins (two TAB (\ t), start a new tuple, for example, tuple [1]).

I use this to split data:

with open(Filename) as f:
    for line in f:
        rawData = line.strip().split('\t')  

And the rest of the logic is still missing (filling in tuples).

( , , - , , . , , .. , . .)

+5
3

, , . Python csv,

csv.register_dialect('mycsv', delimiter='\t', quoting=csv.QUOTE_NONE)
with open(filename, 'rb') as f:
    reader = csv.reader(f, 'mycsv')

. , :

t = tuple(reader)

, cvs .DictReader, , , .

EDIT 2

, namedtuples, . , namedtuple csv:

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

import csv
for line in csv.reader(open("employees.csv", "rb")):
    emp = EmployeeRecord._make(line)
    print emp.name, emp.title
+12

. :

fields = "dow", "open_time", "close _time", "code", "foo", "subject", "bar"
Item = namedtuple('Item', " ".join(fields)) 

.

# this is what your raw data looks like after the split:
#raw_data = ['Monday', '8:00', '10:00', 'ETR_28135', 'lh1n1522', 'Computer science', '1']
data_tuple = Item(**dict(zip(fields, raw_data)))

:

  • zip(fields, raw_data) , [("dow", "Monday"), ("open_time", "8:00"),..]
  • dict() , {"dow": "Monday", "open_time": "8:00", ..}
  • ** Item, Item(dow="Monday", open_time="8:00",..).

, , .

Edit:

, :

data_tuple = Item(*raw_data)

, Item .

+3

If you want to use NamedTuple, you can use a slightly modified version of the example given in the Python documentation:

MyRecord = namedtuple('MyRecord', 'Weekday, start, end, code1, code2, title, whatever')

import csv
for rec in map(MyRecord._make, csv.reader(open("mycsv.csv", "rb"), delimiter='\t')):
    print rec.weekday
    print rec.title
    # etc...
+3
source

All Articles