简体   繁体   中英

get the contents of a specific line from a file in python

I'm trying to get the contents of a line from a file, ie

imagine the file is the following:

line1
line2
line3

and then say the function that reads a specific line is lineget

unLine = lineget(2) 
print(unLine)

and then i'd like the output to be something like:

>>> line2

There's linecache module which you can use:

import linecache

line_num = 2
line = linecache.getline("file.txt", line_num)
print(line)
# other operations
linecache.clearcache()  # after you finished work with file(-s)

You can also apply generator with unpacking:

line_num = 2
with open("file.txt") as f:
    *_, line = (f.readline() for _ in range(line_num))
print(line)

You can also use for loop:

line_num = 2
with open("file.txt") as f:
    for i, line in enumerate(f):
        if i == line_num - 1:
            break
    else:
        line = ""
print(line)

To do work with files there is a concept of context magagers that is usefull to look at. The reason is that we must remember to open/close files as shown below:

fname = "myfile.txt" # Name of file 

# 1. Opening, reading and closing file
FILE = open(fname)
for line in FILE:
    print(line)
FILE.close()

# 2. Use the 'with' context manager to manage opening/closing
with open(fname) as FILE:
    for line in FILE:
        print(line)

Now that we want read in data we must clearly add it to a variable

fname = "myfile.txt" # Name of file 

# 1. Read data, simple
with open(fname) as FILE:
    data = []
    for line in FILE:
            data.append(line)

# 2. Read data directly into the variable
with open(fname) as FILE:
    data = list(FILE)

Maybe we want to strip 'newlines' at the end, this we can do by "stripping" the '\n' character:

fname = "myfile.txt" # Name of file 

# 1. Read data and strip 'newlines', simple
with open(fname) as FILE:
    data = []
    for line in FILE:
        data.append( line.rstrip() )

# 2. Read data and strip newlines using `map` function
with open(fname) as FILE:
    data = map(str.rstrip, FILE)

Finally, we want to get a few specific lines. This we can do with a simple if statement:

fname = "myfile.txt" # Name of file 
readLines = [0, 2, 4] # Lines to be read from file, zero indexed

# 1. Read data from specific lines and strip 'newlines', simple
with open(fname) as FILE:
    data = []
    for line in FILE:
        if idx in readLines:
            data.append( line.rstrip() )

# 2. Read data from specific lines and strip newlines using 'list comprehension'
with open(fname) as FILE:
    data = [ line.rstrip() for idx, line in enumerate(FILE) if idx in readLines ]

One option is:

def lineget(file, line):
    with open(file, 'r') as f:
        lines = file.readlines()
    
    return lines[line-1]

Edit: As mentioned by @Olvin Roght (thank you for the feedback), for files with lots of lines, it is not efficient to read every line in the file, especially if the line of interest is near the top. The following could be used instead:

def lineget(file, line_num):
    f = open(file)
    
    for i, line in enumerate(f):
        if i == (line_num - 1):
            f.close()
            return line

I hope this helps!

Something like this should work:

def lineget(filename,linenumber):
    f = open(filename,"r")
    all_lines = f.readlines()
    f.close()
    return all_lines[linenumber-1]

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