简体   繁体   English

Python-读取文件中的线对

[英]Python - Reading pairs of lines in a file

I am wanting to read pairs of lines in from a file, and perform operations on them. 我想从文件中读取成对的行,并对它们执行操作。 How do I go about doing this in Python? 如何在Python中执行此操作?

I can read the file once with the code below, but I don't know how to turn this into being able to read a whole file of lets say 20 lines, with the rest of my code having to operate on the 10 sets of data that the 20 line file has. 我可以使用下面的代码读取一次文件,但是我不知道如何将其转换为能够读取20行的整个文件,而我的其余代码必须处理10组数据20行文件具有的 There will always be an even amount of lines in the input file. 输入文件中总会有偶数行。

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))

Input: 输入:

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

Output: 输出:

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

This is one easy way to do: 这是一种简单的方法:

with open('file.txt') as f:
    lines = f.readlines()

x = 0
while x < len(lines):
    print('Sum of favourite numbers for {}: {}'.format(lines[x+1], sum(map(int, lines[x].split(',')))))
    x += 2

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

I propose to iterate manually in the file with next and use an infinite loop. 我建议使用next在文件中手动进行迭代,并使用无限循环。

When there are no more lines, next throws StopIteration exception, that's where we break the loop. 当没有更多的StopIterationnext抛出StopIteration异常,这是我们中断循环的地方。

Then the classic elegant way of summing a comma-separated list of integers is to split then map to integer conversion and feed to sum 然后,以逗号分隔的整数列表求和的经典优雅方法是拆分然后映射到整数转换并馈入sum

import sys

with open("test.txt") as infile:
    while True:
        try:
            total = sum(map(int,next(infile).split(",")))
            name = next(infile).rstrip()  # remove linefeed from name
            print("Sum of favourite numbers for {} : {}".format(name,total))
        except StopIteration:
            break

prints: 印刷品:

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

If the file has an odd number of lines, the last line information is dropped since the StopIteration exception happens when reading the name information. 如果文件的行数为奇数,则将删除最后一行信息,因为在读取名称信息时会发生StopIteration异常。

In Python 3.4+ (3.6+ for the f-string usage), how about this: 在Python 3.4+(f字符串用法为3.6+)中,该如何做:

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}")

Note that I did not neglect the with ... context manager - Path() handles that for you. 请注意,我没有忽略with ...上下文管理器Path()为您处理该问题。

I'm not clear on what you're trying to do with the 'name' line - looks like a no-op, which is how I coded it, but you could wrap the l.split() in reversed() to flip the order. 我不清楚您要如何处理“名称”行-看起来像是无操作,这就是我的编码方式,但是您可以将l.split()包装在reversed()以进行翻转命令。

Have a look at itertools.islice: https://docs.python.org/3/library/itertools.html#itertools.islice 看看itertools.islice: https ://docs.python.org/3/library/itertools.html#itertools.islice

from itertools import islice

with open(<path>) as f:
    lines = list(islice(f, 2))
    while lines:
        print(repr(lines))
        lines = list(islice(f, 2))

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

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