从文件行分组成对的文件中获取输入

2024-04-26 06:57:40 发布

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

所以我必须读一个文件,每次我读这个文件时,我必须把行成对地存储在变量中,并用输入数据做各种事情

我的问题是如何将这些行成对地“分组”,例如,如果我在第一行中取三个最喜欢的数字,在第二行中取他们的名字和姓氏,并在整个文件中发生这种情况?为了简单起见,我将它设置为只打印出我要存储的内容

array = []
userInput = sys.stdin
array.append(userInput.readline().strip())
firstName,lastName = map(str,userInput.readline().split(" "))

print(firstName)
print(lastName)
print(array)

输入示例如下:

1 2 3
John Doe
4 5 6
Queen Mary 

文本文件中的输出示例如下:

John
Doe
['1 2 3']
Queen
Mary
['4 5 6']

Tags: 文件数据示例readline数字firstnamejohn事情
3条回答

您可以在一个循环中readline两次,然后将它们都附加到数据结构中,等等:

伪码

dataread = []

with open('file', 'r') as f:
    while f still has lines:
        twolines = [f.readline()]   # add strip/split as needed
        twolines.append(f.readline()) 
        dataread.append(twolines)

您可能需要处理异常

阅读之后,您可以按自己喜欢的方式处理每组两行

高效内存解决方案

使用一个切换标志,您可以每隔一行切换一次,并将内容打印到输出文件(因此,您的内存一次只能保存mximum的内容2行):

with open('infile.txt') as in_file, 
    open('outfile.txt', 'w') as out_file:
        flag = 0
        for line in in_file:
            if not flag:
                s3 = [line]
                flag = 1
            else:
                s1, s2 = line.split()
                print(s1, end = "\n", file = out_file)
                print(s2, end = "\n", file = out_file)
                print(repr(s3), end = "\n", file = out_file)
                flag = 0
from itertools import zip_longest

def read_lines_in_batches(file_path, n = 1):
    with open(file_path) as fh:
        fhs = [fh] * n
        for batch in zip_longest(*fhs):
            yield [line for line in batch if line]

for lines in read_lines_in_batches('foo/bar.txt', 3):
    print(lines)

相关问题 更多 >