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

2024-10-06 08:07:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从文件中获取一行的内容,即

假设文件如下所示:

line1
line2
line3

然后说读取特定行的函数是lineget

unLine = lineget(2) 
print(unLine)

然后我希望输出类似于:

>>> line2

Tags: 文件函数内容printline1line2line3lineget
3条回答

要处理文件,有一个上下文管理器的概念,可以查看它。原因是我们必须记住打开/关闭文件,如下所示:

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(filename,linenumber):
    f = open(filename,"r")
    all_lines = f.readlines()
    f.close()
    return all_lines[linenumber-1]

有一个^{}模块可供使用:

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)

相关问题 更多 >