Let me try to lay this out. I have a text file, each line of the text file is a different string. My trouble is if I want to grab line 3. When I try to use file.readline(3)
or file.read(3)
I will get the first 3 characters of the first line of the text file instead of all of line 3. I also tried file.readlines(3)
but that just returned ['one\n']
which happens to yet again be the first line with [' \n']
around it. I am having more trouble with this that I already should be but I just gave up and need help. I am doing all of this through a discord bot if that helps, though that shouldn't be affecting this.

- 47
- 1
- 7
-
1`file.readlines()[3]` – Barmar Dec 14 '20 at 18:57
2 Answers
as what Barmar said use the file.readlines(). file.readlines makes a list of lines so use an index for the line you want to read. keep in mind that the first line is 0 not 1 so to store the third line of a text document in a variable would be line = file.readlines()[2]
.
edit: also if what copperfield said is your situation you can do:
def read_line_from_file(file_name, line_number):
with open(file_name, 'r') as fil:
for line_no, line in enumerate(fil):
if line_no == line_number:
file.close()
return line
else:
file.close()
raise ValueError('line %s does not exist in file %s' % (line_number, file_name))
line = read_line_from_file('file.txt', 2)
print(line)
if os.path.isfile('file.txt'):
os.remove('file.txt')
it's a more readable function so you can disassemble it to your liking

- 81
- 6
-
Thank you, this ended up helping. I just replaced the line with `line = file.readlines()[2]`, adapted it for correct variable names, and it worked. – codingMakesMeCry Dec 15 '20 at 16:30
-
no problem I like helping people with their coding problems to clear my head of my coding problems. in fact it usually gives me good ideas on how to work around my problems. – MI HAEL Dec 15 '20 at 17:28
-
you don't need to explicitly close the the file if you use the `with` statement, that is basically the whole point of it XD – Copperfield Dec 15 '20 at 22:12
-
when i ran it yes you did I don't know why. I opened the same file later on after implementing it and it said it was open elsewhere. and when I added it it fixed it. idk why but this code snippet is cursed. – MI HAEL Dec 17 '20 at 01:31
unfortunately you just can't go to a particular line in a file in a simple easy way, you need iterate over the file until you get to the desire line or know exactly where this line start withing the file and seek it and then read one line from it
for the first you can do:
def getline(filepath,n):
with open(filepath) as file:
for i,line in enumerate(file):
if i == n:
return line
return ""
Of course you can do file.readlines()[2]
but that read ALL the file and put ALL its lines it into a list first, which can be a problem if the file is big
For the other option check this answer here

- 8,131
- 3
- 23
- 29