简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM