Reading Lines in file using function
Question:
I have tried to create a function called parseGameFile which when called can print a specific line in the file. So variable tc = line 1 and variable (ts) is the rest of the lines in the file, but I have tried to create a loop that goes through and returns all the lines. But I am not sure how to create the loop for when ts[0] or any other index it will return the second line in the file.
For example, my file contains the contents below, and if I call variable (ts) it will return ‘7D’ and if I call ts[0] it return the line ‘AH 2D 5H 2H’
7D
AH 2D 5H 2H
AC 3D 4C KC
AS 2S 4S 3S
AD 4H QD 6D
4D 7S 3H JD
7D 5D 7C 3C
KS KD QS 5S
7H QC QH 2C
JH JC KH 6C
5C 6S 6H JS
def parseGameFile(fname):
f = open(fname, 'r')
contents = f.readlines()
for line in contents:
print(line)
tc = contents[0]
return tc
for line in contents
Answers:
You are using .readlines()
, so you are almost done already.
def get_kth_line(fname, k):
with open(fname) as f:
contents = f.readlines()
return contents[k]
k = 1 # 2nd line, due to zero-origin
print(get_kth_line("game.csv", k))
The piece you were missing is the [k]
dereference
in the return
statement.
Feel free to adjust by +1
if you find zero-origin
inconvenient.
Note that requesting a line beyond EOF will
helpfully report IndexError.
I have tried to create a function called parseGameFile which when called can print a specific line in the file. So variable tc = line 1 and variable (ts) is the rest of the lines in the file, but I have tried to create a loop that goes through and returns all the lines. But I am not sure how to create the loop for when ts[0] or any other index it will return the second line in the file.
For example, my file contains the contents below, and if I call variable (ts) it will return ‘7D’ and if I call ts[0] it return the line ‘AH 2D 5H 2H’
7D
AH 2D 5H 2H
AC 3D 4C KC
AS 2S 4S 3S
AD 4H QD 6D
4D 7S 3H JD
7D 5D 7C 3C
KS KD QS 5S
7H QC QH 2C
JH JC KH 6C
5C 6S 6H JS
def parseGameFile(fname):
f = open(fname, 'r')
contents = f.readlines()
for line in contents:
print(line)
tc = contents[0]
return tc
for line in contents
You are using .readlines()
, so you are almost done already.
def get_kth_line(fname, k):
with open(fname) as f:
contents = f.readlines()
return contents[k]
k = 1 # 2nd line, due to zero-origin
print(get_kth_line("game.csv", k))
The piece you were missing is the [k]
dereference
in the return
statement.
Feel free to adjust by +1
if you find zero-origin
inconvenient.
Note that requesting a line beyond EOF will
helpfully report IndexError.