Here is some code that uses only a single for loop and a single if statement to check if a line in the read_file is present in the batch_file (I assume that is what you want to check!).
Just open the files and use readlines()
to get all the lines individually. Then just iterate through all the lines in the read_file and check if they are in the list of lines in the batch_file (Note that readlines() generates a list whose individual entries are the contents of each line including the ending \n
character).
read_file = "a.txt"
batch_file = "b.txt"
with open(read_file) as a:
a_lines = a.readlines()
with open(batch_file) as b:
b_lines = b.readlines()
for line in a_lines:
if line in b_lines:
print(line.strip())
Edit:
To get the number of the line in the read_file that contains the match to a line in the batch_file, you have to change the way you go through the read_file. In this case, use enumerate
to get not only the content of each line but also the number of each line (in this case stored in the variable i
).
I then just printed the number and content of the matched lines in the read_file and the batch_file.
i
gets you the number of the line in the read_file.
a_lines[i]
gets you the corresponding list item (= content of the line)
b_lines.index(line)
gets you the number of the item line
in the b_lines
list (= number of the line in the batch_file)
line.strip()
gets you the content of that line in the batch_file without the trailing \n
character.
See the attached expanded code:
read_file = "a.txt"
batch_file = "b.txt"
with open(read_file) as a:
a_lines = a.readlines()
with open(batch_file) as b:
b_lines = b.readlines()
for i, line in enumerate(a_lines):
if line in b_lines:
print("Number of line in read_file is %i" % i)
print("Content of line in read_file is %s" % a_lines[i].strip())
print("Number of line in batch_file is %i" % b_lines.index(line))
print("Content of line in batch_file is %s" % line.strip())