I have this function in python 3 that works almost as I want it to work:
def read_people_from_file(filename):
"""Function that reads a file and adds them as persons"""
print("reading file")
try:
with open(filename, 'rU') as f:
contents = f.readlines()
except IOError:
print("Error: Can not find file or read data")
sys.exit(1)
#Remove blank lines
new_contents = []
for line in contents:
if not line.strip():
continue
else:
new_contents.append(line)
#Remove instructions from file
del new_contents[0:3]
#Create persons (--> Here is my problem/question! <--)
person = 1*[None]
person[0] = Person()
person[0] = Person("Abraham", "m", 34, 1, 140, 0.9, 90, 0.9, 0.9)
for line in new_contents:
words = line.split()
person.append(Person(words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7], words[8]))
return person
In the last chunk of code, below "#Create persons", is a thing that I have not figured out how to do.
How do I create the empty list of persons and then add persons from the file?
If I remove the hard coded person named "Abraham", my code does not work.
The file is a text file with one person per row with the attributes coming after the name.
Part of the Person class looks like this:
class Person:
def __init__(self, name=None, gender=None, age=int(100 or 0), beauty=int(0), intelligence=int(0), humor=int(0), wealth=int(0), sexiness=int(0), education=int(0)):
self.name = name
self.gender = gender
self.age = age
self.beauty = beauty
self.intelligence = intelligence
self.humor = humor
self.wealth = wealth
self.sexiness = sexiness
self.education = education
I hope that the above code is self explanatory.
I suspect that there is some more pythonian way of doing what I want.
Any help is appreciated.
You can do
persons = []
...
for line in new_contents:
words = line.split()
persons.append(Person(...))
There's always:
persons = [Person(*line.split()) for line in new_contents]
This is probably the simplest way to do what you want:
def readfile():
data = open("file path to read from","r") #opens file in read mode
people = []
for line in data: #goes through each line
people.append(Person(*line.split())) #creates adds "Person" class to a list. The *line.split() breaks the line into a list of words and passes the elements of the list to the __init__ function of the class as different arguments.
return people
Related
This is currently my code for reading through a CSV file, Creating a person object, and adding each person to a list. One line Example input: John,Langley,1,2,2,3,5
When i print(per) each time after creating a person object. My output is correct, but as soon as i add that person to the list i made, the numeric values AKA 'traits' for that person are all the same as the last persons traits in the CSV file.
For Example:
John,Langley,1,2,2,3,5 --(add to list)-->John,Langley,1,1,1,1,1
Isabel,Smith,3,2,4,4,0 --(add to list)-->Isabel,Smith,1,1,1,1,1
John,Doe,1,1,1,1,1 --(add to list)-->John,Doe,1,1,1,1,1
This is impacting me with continuing because i need the person objects' traits to be valid in order to perform analysis on them in the next couple methods. PLEASE IGNORE MY PRINT STATEMENTS. THEY WERE FOR MY DEBUGGING PURPOSES
def read_file(filename):
file = open(filename, "r", encoding='utf-8-sig')
Traits_dict = {}
pl = []
next(file)
for line in file:
line = line.rstrip('\n')
line = line.split(',')
first = str(line[0].strip())
last = str(line[1].strip())
w = line[2].strip()
hobby = line[3].strip()
social = line[4].strip()
eat = line[5].strip()
sleep = line[6].strip()
Traits_dict["Work"] = w
Traits_dict["Hobbies"] = hobby
Traits_dict["Socialize"] = social
Traits_dict["Eat"] = eat
Traits_dict["Sleep"] = sleep
per = Person(first, last, Traits_dict)
print(per)
pl.append(per)
print(pl[0])
print(pl[1])
print(pl[2])
print(pl[3])
print(pl[4])
return pl
All the Traits_dict = {} are the same to all object since you initiating the dict before the loop so it's giving each Person object the same dict reference in it.
You can put the Traits_dict = {} inside the loop that it will create each Person a new dict
for line in file:
Traits_dict = {}
I have a text file with contents like this (format ):
Alice:ECE505,56:HIS230,78:REC345,98
Bob:MATH300,78:IN121,79:LEC091,23:ARC,32:WER720,67
I would like to add each class name and score to its perspective person.
So far I have something like this:
all_stu = record_pb2.Result()
person = all_stu.student.add()
cl = person.courses.add()
with open(textfile, "r") as readfile:
txt = readfile.read()
for line in txt.split('\n'):
segment = line.split(':')
person.name = segment[0]
classes = segment[1:]
#I have tried this but it only returns the last class and score
for c in classes:
cname, score = c.split(',')
cl.name = cname
cl.score = score
I know my loop only returns the last class name and score but how do I store each of the classes and scores for the respective person/line with Google Protobuf? Thanks in advance!
You forget to add each each person you read from the file. Next you need to add each class your find in the person object. You now only create those objects once and thus you overwrite them all the time.
all_stu = record_pb2.Result()
person = all_stu.student.add()
with open(textfile, "r") as readfile:
txt = readfile.read()
for line in txt.split('\n'):
segment = line.split(':')
person = all_stu.student.add()
person.name = segment[0]
classes = segment[1:]
#I have tried this but it only returns the last class and score
for c in classes:
cl = person.courses.add()
cname, score = c.split(',')
cl.name = cname
cl.score = score
Here I do make the assumption that courses is a repeated field.
so i created a class that holds a baseball players year, name, stats. I am now trying to read from a txt file that holds the players information and create a list of objects. I cannot seem to figure out how to do so.
Here is the class:
class PlayersYear:
def __init__(self, year, player, stats):
self.__year = int(year)
self.__player = player
self.__stats = stats
Now I am trying to read from a file that list the stats like this lets call it baseball.txt:
1971Hank Aaron:162:22:3:47:495
2002Barry Bonds:149:31:2:46:403
1974Rod Carew:218:30:5:3:599
i am trying to read these in an create an PlayersYear object and append it to a list. I am completely lost and would appreciate some help. Thank you!
This is what I have and I know its wrong
def readPlayerFile(filename):
baseball = []
file_in = open(filename, 'r')
lines = file_in.readlines()
for i in lines:
baseball.append(PlayersYear(year, name, stats))
file_in.close()
return baseball
Is this will help you? It just separate the player name, year and status
def playerList(fileName):
file = open(fileName, 'r')
nameList = []
for line in file:
line = line[4:]
name = line.split(":")[0]
nameList.append(name)
return nameList
def statusList(fileName,satusLocation):
file = open(fileName, 'r')
statusList = []
for line in file:
status = line.split(":")[satusLocation]
statusList.append(status)
return statusList
def yearList(fileName):
file = open(fileName, 'r')
years = []
for line in file:
line = line[:4]
years.append(line)
return years
I am attempting to read in individual elements of a file. In this example, the first element of each line is to be the key of a dictionary. The next five elements will be a corresponding value for said key in list form.
max_points = [25, 25, 50, 25, 100]
assignments = ['hw ch 1', 'hw ch 2', 'quiz ', 'hw ch 3', 'test']
students = {'#Max': max_points}
def load_records(students, filename):
#loads student records from a file
in_file = open(filename, "r")
#run until break
while True:
#read line for each iteration
in_line = in_file.readline()
#ends while True
if not in_line: break
#deletes line read in
in_line = in_line[:-1]
#initialize grades list
grades = [0]*len(students['#Max'])
#set name and grades
name, grades[0], grades[1], grades[2], grades[3], grades[4] = in_line.split()
#add names and grades to dictionary
students[name] = grades
print name, students[name]
filename = 'C:\Python27\Python_prgms\Grades_list.txt'
print load_records(students, filename)
The method I have now is extremely caveman, and I would like to know what the more elegant, looping method would be. I have been looking for a while, but I can't seem to find the correct method of iteration. Help a brotha out.
Another way of doing it:
def load_records(students, filename):
with open(filename) as f:
for line in f:
line = line.split()
name = line[0]
students[name] = map(int, line[1:])
print name, students[name]
It seems a bit strange that the student dictionary contains both the scores and a parameter #Max though - a key has two meanings, is it a student's name or parameter's name? Might be better to separate them.
I had an assignment similar to this last year.
def load_records(students, filename):
file = open(filename, 'r')
s = ""
while s != None: # loop until end of file is reached
s = file.readline()
# manipulate s how you need
Also, you should use inline comments like above, it makes the code much easier to read compared to how you have it now.
I am trying to read from a file into a dictionary. The lane.split() method will not work as I am formatting my file over separate lines, with too many spaces.
in inventory2
(item, description) = line.split()
ValueError: too many values to unpack
Here is my text file. Key \n Value.
Key
A rusty old key, you used it to gain entry to the manor.
A stick
You found it on your way in, it deals little damage.
Health potion
A health potion, it can restore some health.
Any solutions to this would be much appreciated.
def inventory2():
inventory_file = open("inventory_test.txt", "r")
inventory = {}
for line in inventory_file:
(item, description) = line.split()
inventory[(item)] = description
#invenory = {inventory_file.readline(): inventory_file.readline()}
print(line)
inventory_file.close
You are looping over each line in the file, so there will never be a line with both key and value. Use the next() function to get the next line for a given key instead:
def inventory2():
with open("inventory_test.txt", "r") as inventory_file:
inventory = {}
for line in inventory_file:
item = line.strip()
description = next(inventory_file).strip()
inventory[item] = description
return inventory
or, more compact with a dict comprehension:
def inventory2():
with open("inventory_test.txt", "r") as inventory_file:
return {line.strip(): next(inventory_file).strip() for line in inventory_file}
Here is another way:
def inventory2():
inventory_file = open("inventory_test.txt", "r")
inventory = {}
lines = inventory_file.readlines()
x = 0
while (x < len(lines)):
item = lines[x].strip()
description = lines[x+1].strip()
inventory[item] = description
x += 2
print inventory
return inventory
Outputs:
{'Health potion': 'A health potion, it can restore some health.', 'A stick': 'You found it on your way in, it deals little damage.', 'Key': 'A rusty old key, you used it to gain entry to the manor.'}