Search code examples
pythontextreadlinetxt

How do I read a specific line on a text file?


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.


Solution

  • 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