Ask coding questions

← Back to all posts
Help!
LukeShomper (26)

So I need to read a file I can read a whole file but I cant figure out howto read 1 line of a file Help!

Answered by PDanielY (629) [earned 5 cycles]
View Answer
Commentshotnewtop
PDanielY (629)

file = open(filename,what you want to do)
file.readline()

LukeShomper (26)

@PDanielY Ok but how do I set line 1 to a var

PDanielY (629)

file = open(filename,what you want to do)
[variable name] = file.readline()

LukeShomper (26)

@PDanielY ok that works for line 1, how would i make it read line 3
because file.readline() reads line 1, but I need it to read line 3

PDanielY (629)

@LukeShomper you have to do it more than once. Example:
file.readline() line1
file.readline() line 2
file.readline() line 3

Rileygamer21 (34)

Can u elaborate on that? Cuz im not sure what u mean

LukeShomper (26)

@Rileygamer21 So If I have a file thats like
line 1: Bob
line 2: Ross
I need to make it so if I do this
print(file.line1) or somthing like that
it will print bob and not
bob
ross

LukeShomper (26)

And I need it to be in a var

Rileygamer21 (34)

@LukeShomper then what about
first_name = bob
last_name = ross <--- add a extra space between = and ross
print(last_name + first name)