Albatrosz Aladin
biologia
9.a
2
Albatrosz Aladin
kemia
9.a
2
Albatrosz Aladin
osztalyfonoki
9.a
1
Antilop Anett
testneveles
9.a
5
Bagoly Barbara
nemet
9.a
3
My code:
class tan:
nev = []
tantargy = []
osztaly = []
oraszam = []
def fel1(self):
print("1.feladat")
f = open("/home/i3hunor/Programozas/Info_erettsegi/Erettsegi/2s_2019maj-ideg/Forrasok/4_Tantargyfelosztas/beosztas.txt","r")
for sor in f:
tomb = sor.rstrip()
print(self.nev,"\n",self.tantargy)
Expected output:
(self.nev) (in list or any format)
Albatrosz Aladin,Albatrosz Aladin,Albatrosz Aladin,Antilop Anett,Bagoly Barbara
(self.tantargy)
biologia, kemia, osztalyfoniku, testneveles, nemet
Is it possible to do this? What did i do wrong and why can't I use smt like tomb[1]
.
Sorry if my question is not understandable, i can't explain it more cause of my lack of english skills.
CodePudding user response:
Are you trying to read a file with tokens separated by new-line, and put them in a list? Take a look here: https://stackoverflow.com/a/71978699/13238310
CodePudding user response:
Read all the lines, then iterate on them by batch of 4, and save them in the appropriate lists
class tan:
def __init__(self):
self.nev = []
self.tantargy = []
self.osztaly = []
self.oraszam = []
def fel1(self):
with open("test.txt") as f:
lines = f.readlines()
for i in range(0, len(lines), 4):
n, t, os, ora = lines[i:i 4]
self.nev.append(n.rstrip())
self.tantargy.append(t.rstrip())
self.osztaly.append(os.rstrip())
self.oraszam.append(ora.rstrip())
t = tan()
t.fel1() # load data
print(t.nev)
# ['Albatrosz Aladin', 'Albatrosz Aladin', 'Albatrosz Aladin', 'Antilop Anett', 'Bagoly Barbara']
print(t.tantargy)
# ['biologia', 'kemia', 'osztalyfonoki', 'testneveles', 'nemet']
CodePudding user response:
You would need to initialize the lists, then read and append the appropriate elements to these lists.
class Tan:
def __init__(self):
self.nev = []
self.tantargy = []
self.oztaly = []
self.oraszam = []
def read(self):
file = open("test.txt", "r", encoding="utf-8")
line = file.readline().replace("\n", "")
count = 0
while line != "":
if count%4 == 0:
self.nev.append(line)
elif count%4 == 1:
self.tantargy.append(line)
elif count%4 == 2:
self.oztaly.append(line)
else:
self.oraszam.append(line)
count = 1
line = file.readline().replace("\n", "")
file.close()
def display(self):
print(self.nev)
print(self.tantargy)
print(self.oztaly)
print(self.oraszam)
tan = Tan()
tan.read()
tan.display()