我有两个文本文件,我想逐行读取它并检查是否发生匹配,如果它发生则打印或者什么都不做。但是在下面的代码中,它仅检查第一个文件的第一行,并检查第二个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 + '"')
我的数据就像
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...
答案 0 :(得分:2)
要在两个迭代器上“并行”循环,使用内置的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
反之亦然,从预期较小的文件构建dict,然后使用它逐行检查预期会更大的文件。
答案 1 :(得分:0)
将读取放在同一个循环中。两个文件的最小工作示例分别名为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)
行。
答案 2 :(得分:0)
以下是@Alex Martelli's dict
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))
Data1 is changed from 1 to 4
Data2 is changed from 2 to 4
Data3 is changed from 3 to 6