Val
Val

Reputation: 21

Reading a file of data and making a list from the objects

I have some data in a separate file that is like this:

bob 11 20
sam 30 19
jay 50 10

and so on... I am trying to :

  1. Open the file.
  2. Read each line.
  3. Make an object with the data from that line.

I'm going about it like this :

with open("data.txt") as f:
    for lines in f:
        f.readlines()
data = lines.split()

Is this the correct way to make sure each line is kept in it's own list? Like for example [bob, 11, 20] ?

Upvotes: 0

Views: 1161

Answers (5)

Free Code
Free Code

Reputation: 283

This code will help you:

data = []
lines = [line.rstrip('\n') for line in open('data.txt')]
for line in lines:
   data.append({'name' : line.split()[0], 'something1' : line.split()[1], 'something2' : line.split()[2]})

you can loop or even get data info very easy

Upvotes: 0

balderman
balderman

Reputation: 23815

I have defined a Person class (as an example for an object) that is created using each line of the file

class Person:
    def __init__(self, name, age, weight):
        self.name = name
        self.age = age
        self.weight = weight

    def __str__(self):
        return 'name:{},age:{},weight:{}'.format(self.name, self.age, self.weight)


persons = []
with open('data.csv', 'r') as f:
    lines = f.readlines()
    for line in lines:
        fields = line.split(' ')
        persons.append(Person(fields[0], fields[1], fields[2]))
for person in persons:
    print(person)

Upvotes: 0

Ian
Ian

Reputation: 11

Just from dealing with lots of lists today, I can offer another solution: to get each line as a list and make a list of those lists, e.g. [['bob 11 20'], ['sam 30 19'], ['jay 50 10']] I used this function:

def read(): reader = csv.reader(open("list.txt"), delimiter="\t") list = [r for r in reader] print(list)

There are a lot of ways to deal with lists and the one that works for your project is the 'correct' way. Earlier today I was teasing apart sqlalchemy queries into dictionaries and converting those into strings and piping those out to datetime formatting, them appending them all back together! You can preserve the lines individually if thats what you need, or by iterating over them again with a function, pull out more granular data for your project. Good luck!

Upvotes: 0

Aviv Bar-el
Aviv Bar-el

Reputation: 81

No this will give you only the last line, you should instead do it like this:

data = []
with open("data.txt") as f:
    for line in f:
        data.append(line.split())

Upvotes: 0

blhsing
blhsing

Reputation: 106713

You can iterate over the file generator in a list comprehension and split each line into lists of items:

with open("data.txt") as f:
    data = [line.split() for line in f]

Upvotes: 1

Related Questions