Reputation: 95
I have an assignment in which I have to read a file "words.csv":
Hemuli,Muumipappa,13,4
Abbath,Fenriz,6,6
And I should print it out as following:
Hemuli 13 - 4 Muumipappa
Abbath 6 - 6 Fenriz
My code so far:
def nayta_tulokset(words):
with open(words) as tulos:
tulokset = tulos.read()
a = tulokset.split(",")
print(a)
This gives me a following list
:
['Hemuli', 'Muumipappa', '13', '4\nAbbath', 'Fenriz', '6', '6']
Which is exactly what I want, but how do I proceed to strip down that \n? The "4" and "Abbath" should be in one of their own indexes. Can't seem to figure it out... After that I could use indexes and print out with format().
Upvotes: 2
Views: 4410
Reputation: 16271
A solution that makes use of list comprehension and the string format as above could be:
def nayta_tulokset(words):
with open(words, 'r') as f:
return list(map(lambda x:"{} {} - {} {}".format(x[0],x[2],x[3],x[1]), map(lambda x:x.split(','),f.read().split())))
so
nayta_tulokset('words.csv')
['Hemuli 13 - 4 Muumipappa', 'Abbath 6 - 6 Fenriz']
Upvotes: 1
Reputation: 7504
You can use splitlines()
while reading
def nayta_tulokset(words):
with open(words) as tulos:
return tulos.read().splitlines()
# output: ['Hemuli,Muumipappa,13,4', 'Abbath,Fenriz,6,6']
Then split the string .split(',')
for i in nayta_tulokset(words):
_f = i.split(",")
print("{} {} - {} {}".format(_f[0], _f[-2], _f[-1], _f[1]))
# Hemuli 13 - 4 Muumipappa
# Abbath 6 - 6 Fenriz
Upvotes: 4
Reputation: 14689
In order to get the output you want, you need to read each line separately and print it out as expected.
Building up, on your code, here how you can proceed
def nayta_tulokset(words):
with open(words) as tulos:
for line in tulos.read().split('\n'):
a = line.split(",")
print("{} {} - {} {}".format(a[0], a[2], a[3], a[1]))
instead of using tulos.read().split('\n')
, you can use tulos.readlines()
, which will take care of reading you file into a list of lines. So after refactoring, the code will look like this:
def nayta_tulokset(words):
with open(words) as tulos:
for line in tulos.readlines():
a = line.split(",")
print("{} {} - {} {}".format(a[0], a[2], a[3], a[1]))
More Details: I guess the only somewhat ambiguous part of the code is the following:
"{} {} - {} {}".format(a[0], a[2], a[3], a[1])
Which is equivalent to the following string concatenation:
a[0] +" " + a[2] +" - " + a[3] + " " +a[1]
Upvotes: 1
Reputation: 2124
You might want to use regular expressions. Like so:
import re
def nayta_tulokset(words):
with open(words) as tulos:
tulokset = tulos.read()
#a = re.findall(r"[\w']+", tulokset)
a = re.split(",\n", tulokset)
This should give you:
['Hemuli', 'Muumipappa', '13', '4', 'Abbath', 'Fenriz', '6', '6']
Upvotes: 0