Skip to main content
 首页 » 编程设计

Python之读取文件中的行对

2025年05月04日9yxwkf

我想从文件中读取成对的行,并对它们执行操作。我该如何在 Python 中执行此操作?

我可以使用下面的代码读取文件一次,但我不知道如何将其转换为能够读取整个文件(比方说 20 行),而我的其余代码必须在第 10 行上运行20 行文件具有的数据集。输入文件中的行数总是偶数。

import sys 
input = sys.stdin 
favouriteNumbersInput = [] 
 
with open("test.txt", 'r') as infile: 
    lines_gen = islice(infile, 2) 
    for line in lines_gen: 
 
        favouriteNumbersInput.append(line.strip(' ').strip('\n')) 
        firstName,lastName = map(str,line.split(" ")) 
        favouriteNumbers = list(map(int, favouriteNumbersInput)) 

输入:

3, 1, 5, 2 
John Doe 
5, 1, 6, 7 
Jane Doe 

输出:

Sum of favourite numbers for John Doe: 11 
Sum of favourite numbers for Jane Doe: 19 

请您参考如下方法:

在 Python 3.4+(3.6+ 用于 f-string 用法)中,怎么样:

from pathlib import Path 
 
flines = Path('test.txt').read_text().splitlines() 
nums =  [sum([int(n) for n in l.split(',')]) for l in flines[0::2]] 
names = [' '.join(l.split()) for l in flines[1::2]] 
 
for name, num in zip(names, nums): 
    print(f"Sum of favorite numbers for {name}: {num}") 

请注意,我没有忽略 with ... 上下文管理器 - Path() 会为您处理。

我不清楚你想用“name”行做什么 - 看起来像一个空操作,这就是我的编码方式,但你可以包装 l.split() 在 reversed() 中翻转顺序。