2

I am trying to write a simple program that will read a list of users in my AD group and put "***" after a name if its new. It doesnt seem to be working write so I am just wondering where I am going wrong. here is what I have:

list1 = open('testlist.txt', 'r')

for i in list1:
   print(i, end=' ')


list2 = open('NewUserList.txt', 'r+')

for ii in list2:
   if ii not in list1:
      list2.write(ii.strip("\n")+" ***\n")

Example of list1:

Mike Smith
John Smith
Tom Smith

Here is an example of what I am getting in list2 when its done:

Mike Smith
John Smith
Tom Smith
Jerry Smith
Mike Smith ***
John Smith ***
Tom Smith ***
Jerry Smith ***

Obviously this is showing that existing users are new users along with the new user.... What did I do wrong?

Aoxx
  • 55
  • 1
  • 13

2 Answers2

2

list1 is an iterator that ends on the first loop.

Use the split method:

list1 = open('testlist.txt', 'r').read().split('\n')

and you'll find much more peace.

Uriel
  • 15,579
  • 6
  • 25
  • 46
  • I am getting this back: `Traceback (most recent call last): File "C:\Python32\readlist.py", line 1, in list1 = open('testlist.txt', 'r').split('\n') AttributeError: '_io.TextIOWrapper' object has no attribute 'split'` – Aoxx Oct 26 '16 at 16:41
  • Same thing, it appends every name in the list with " ***" – Aoxx Oct 26 '16 at 16:48
2
for i in list1:

list yields the lines, but doesn't store them. You have to keep the values yourself:

s = set()

with open('testlist.txt') as f:
     for line in f:
        s.add(line)
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • I am getting this: `Traceback (most recent call last): File "C:\Python32\readlist.py", line 11, in if ii not in f: TypeError: argument of type '_io.TextIOWrapper' is not iterable` – Aoxx Oct 26 '16 at 17:30
  • We're storing the seen names in the set `s`. Check `if ii not in s:` – Patrick Haugh Oct 26 '16 at 17:36
  • That worked, I was still using f (list1) for my IF statement. thank you. – Aoxx Oct 26 '16 at 17:57