在python中遍历文本文件行

2024-04-20 08:27:47 发布

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

我有两个文本文件,我想逐行阅读并检查是否匹配,如果匹配,则打印或不执行任何操作。但在下面的代码中,它只检查第一个文件的第一行,并检查第二个for循环文件的所有行。但我要检查第一个文件和第二个文件的所有行。我不知道我犯了什么错误。在

with open("changed_commands_from_default_value", "a") \
            as changed_commands_from_default_value, \
     open(command_file, "r") \
            as command_executed_file, \
     open("default_command_values", "r") \
            as default_command_values:
    for default_command in default_command_values:
       for command_executed in command_executed_file:
           only_command = command_executed.split()[0]
           only_default_command = default_command.split()[0]
           if only_command == only_default_command:
               if command_executed != default_command:
                   print("   > The default value " +
                         default_command.rstrip() + " is changed to " +
                         command_executed.rstrip())
                   changed_commands_from_default_value.write(
                       "The default value " + '"' + default_command + '"' +
                       "is changed to " + '"' + command_executed + '"')

我的数据是

^{pr2}$

我想要一个输出

^{3}$

Tags: 文件infromdefaultonlyforvalueas
3条回答

要在两个迭代器上“并行”循环,请使用内置的zip,或者,在python2中,itertools.izip(当然,后者需要在模块的开头使用import itertools)。在

例如,更改:

        for default_command in default_command_values:
            for command_executed in command_executed_file:

进入:

^{pr2}$

这假设两个文件确实是“并行”的,即在1-1个对应的行中。如果不是这样的话,那么最简单的方法(除非文件太大以至于你的内存无法容纳它)是先将一个文件读入dict,然后用dict检查另一个文件。例如:

    cmd2val = {}
    with open("default_command_values", "r") as default_command_values:
        for default_command in default_command_values:
            cmd2val[default_command.split()[0]] = default_command.strip()

然后,分别:

with open(command_file, "r") as command_executed_file:
    for command_executed in command_executed_file:
        only_command = command_executed.split()[0]
        if only_command not in cmd2val: continue   # or whatever
        command_executed = command_executed.strip()
        if command_executed != cmd2val[only_command]:
            # etc, etc, for all output you desire in this case

反之亦然,从预期较小的文件构建dict,然后使用它逐行检查预期较大的文件。在

以下是@Alex Martelli's ^{} suggestion的实现:

#!/usr/bin/env python3
"""Match data in two files. Print the changes in the matched values.

Usage: %(prog)s <old-file> <new-file>
"""
import sys

if len(sys.argv) != 3:
    sys.exit(__doc__ % dict(prog=sys.argv[0]))

old_filename, new_filename = sys.argv[1:]

# read old file
data = {}
with open(old_filename) as file:
    for line in file:
        try:
            key, value = line.split()
            data[key] = int(value)
        except ValueError:
            pass # ignore non-key-value lines

# compare with the new file
with open(new_filename) as file:
    for line in file:
        columns = line.split()
        if len(columns) == 2 and columns[0] in data:
            try:
                new_value = int(columns[1])
            except ValueError:
                continue # ignore invalid lines
            else: # matching line
                value = data[columns[0]]
                if value != new_value: # but values differ
                    print('{key} is changed from {value} to {new_value}'.format(
                        key=columns[0], value=value, new_value=new_value))

输出(对于问题的输入)

^{pr2}$

只要把读数放在同一个循环中。两个分别名为t1.in和t2.in的文件的最小工作示例如下:

with open('t1.in', 'r') as f1:
    with open('t2.in', 'r') as f2:
        while True:
        l1, l2 = f1.readline(), f2.readline() # read lines simultaneously

        # handle case where one of the lines is empty 
        # as file line count may differ
        if (not l1) or (not l2): break
        else: 
            # process lines here

这个例子同时从两个文件中读取行,如果其中一个文件的行数少于另一个文件的行数,则读取min(lines_of_file_1, lines_of_file_2)行。在

相关问题 更多 >