0

I am trying to open two files. The first one (masters) looks like:

ABC0001 \t rest \t of \t line
ABC0002 \t rest \t of \t line
ABC0003 \t rest \t of \t line
...

all of the " \t " are actual tabs in the file and there is other information after each of the item numbers.

The next file (allp) just has item numbers, but they are expanded:

ABC0001
ABC0001.25
ABC0001.56
ABC0001.35
ABC0002
ABC0002.43
ABC0002.97
...

My code so far:

masters = open("masters.txt","r")
allp = open("allp.txt","r")

for line in masters:
  tabloc = line.find("\t")
  product = line[:tabloc]
  info = line[tabloc:]
  for line_2 in allp:
    if product in line_2:
      print 1
    else:
      print 0

My output is all 0s. I have fooled around with it a bit and tried resetting "product" to ABCXXXX. If i print out product before the nested loop, it is correct, but if I print it in the nested loop, it prints the first product however many times, and then every other one is ABCXXXX.

I'm sure my logic could be simplified, but it's not necessary and I can't really think of how to do it as I am still quite new to python.

What I need is to take the main product from the "masters" list and find all of its sub-products in the "allp" list. I need to print each of the sub-products with the info from it's master product.

5
  • What is the output you need? Commented Feb 19, 2013 at 18:30
  • I'm sorry ... I'm having a hard time parsing exactly what it is that you want to see output from your code. Could you please edit your post and be more specific? Commented Feb 19, 2013 at 18:31
  • Sorry about that. Added what I am trying to do. :-) Commented Feb 19, 2013 at 18:35
  • What does this mean "ABC0001 \t rest \t of \t line" ? Commented Feb 19, 2013 at 18:36
  • What is the main product? Commented Feb 19, 2013 at 18:37

1 Answer 1

1

You're going to want

allp = open("allp.txt","r").readlines()

since you do

for line_2 in allp:

within a loop, all the subsequent iterations after the first will be blank.

Edit
As mgilson pointed out, allp.seek(0) at the end of each iteration is also a good way to do it, especially with large files.

Sign up to request clarification or add additional context in comments.

2 Comments

Not a problem. Been there before, very frustrating :-)
Alternatively, you could allp.seek(0) to reset the file object so you can iterate over it again. that might be preferable if your files are HUGE -- If they're reasonable sized though, it doesn't really matter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.