繁体   English   中英

从 python 中的文件中获取特定行的内容

[英]get the contents of a specific line from a file in python

我正在尝试从文件中获取一行的内容,即

想象文件如下:

line1
line2
line3

然后说读取特定行的 function 是lineget

unLine = lineget(2) 
print(unLine)

然后我希望 output 类似于:

>>> line2

您可以使用linecache模块:

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)

您还可以使用解包生成器:

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

您还可以使用 for 循环:

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)

要处理文件,有一个上下文 magagers 的概念很有用。 原因是我们必须记住打开/关闭文件,如下所示:

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)

现在我们要读入数据,我们必须清楚地将其添加到变量中

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)

也许我们想在最后去除“换行符”,我们可以通过“去除” '\n'字符来做到这一点:

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)

最后,我们想要得到一些特定的行。 我们可以用一个简单的 if 语句来做到这一点:

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 ]

一种选择是:

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

编辑:正如@Olvin Roght 提到的(感谢您的反馈),对于有很多行的文件,读取文件中的每一行效率不高,特别是如果感兴趣的行靠近顶部。 可以改用以下内容:

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

我希望这有帮助!

像这样的东西应该工作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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