-2

While trying to solve some python exercices I found myself needing to split a string using the .split with 2 delimiters but i cant make it work. I've searched in other people's questions but the answer is always to use the re.split which i cant use because these are exerceices for class in which i can't use it.

this is my code:

f1=open("data/namesStudents.txt")
f2=open("data/namesGrades.txt")
text=f1.read().split()
text2=f2.read().split("\n")
text2

To put this in context this is an exercice in which i have to get the grades of students off a txt file(they are like this basicly :14 15 14 17\n 14 14\n\n 13 10\n 13 10 11) and then make the average of the grades of each student and add it to the other txt file.

  • @Aran-Fey: that's the wrong dupe, they are not splitting on multiple delimiters and have worded their question wrong. – Martijn Pieters May 27 '18 at 16:22
  • Hmm. Then I suppose I don't understand the question. – Aran-Fey May 27 '18 at 16:23
  • Can you use replace? – supra28 May 27 '18 at 16:24
  • @Aran-Fey: they have lines, each line needs to be split on spaces. – Martijn Pieters May 27 '18 at 16:24
  • In other words, they want to split by spaces and newlines? In that case the duplicate fits, doesn't it? Edit: I see what you're saying. They want a nested list as output, huh. I have to admit, I'm not sure how you arrived at that conclusion. Edit 2: Nvm, I can see it now. Makes sense. – Aran-Fey May 27 '18 at 16:25
  • @MartijnPieters How's [this](https://stackoverflow.com/questions/7680729/how-do-you-split-a-string-to-create-nested-list) for a dupe? – Aran-Fey May 27 '18 at 16:40
  • 2
    @Aran-Fey: that'd answer the direct question on how to split multiple times, yes. This *is* an X-Y problem however. – Martijn Pieters May 27 '18 at 16:45
  • Related/dupe: [How to read each line from a file into list word by word in Python](//stackoverflow.com/q/27722068) – Aran-Fey May 27 '18 at 16:53

1 Answers1

2

You want to split each line you have split out from the file. The first split produces a list of strings, then you need to call split again, on each of those strings:

values_per_line = [line.split() for line in f2.read().split('\n')]

Not that you actually need to split twice. You could just loop directly over the file:

values_per_line = [line.split() for line in f2]

Looping over a file gives you the lines in a file without having to call .read() and splitting.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343