繁体   English   中英

在python中循环浏览文本文件行

[英]Looping through lines of text file in python

我有两个文本文件,我想逐行阅读并检查是否发生匹配,如果匹配,则打印或不执行任何操作。 但是在以下代码中,它仅检查第一个文件的第一行,并检查第二个循环文件​​的所有行。 但是我想检查第一个文件以及第二个文件的所有行。 我不确定自己在犯什么错误。

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 + '"')

我的数据就像

File 1:

Data1 1
Data2 2
Data3 3
Data4 6
Data5 10

File 2:

Data1 4
Data2 4
Data3 6
....

我想有一个输出

Data1 is changed from 1 to 4
Data2 is changed from 2 to 4 and so on...

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

例如,更改:

        for default_command in default_command_values:
            for command_executed in command_executed_file:

变成:

        for default_command, command_executed in zip(
            default_command_values, command_executed_file):

假设这两个文件确实是“平行的”-即以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

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

只需将读取置于同一循环中即可。 两个文件(分别名为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)读取min(lines_of_file_1, lines_of_file_2)行。

这是@Alex Martelli的dict建议的实现

#!/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))

输出(用于问题的输入)

Data1 is changed from 1 to 4
Data2 is changed from 2 to 4
Data3 is changed from 3 to 6

暂无
暂无

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

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