XChikuX XChikuX - 6 months ago 8
Python Question

Reading Specific Python list from a text file

I am currently Trying to read all data Occurring after a colon ':' in a file for example.
In a text file containing only:


SAM Account Type : 805306368


with open("Sample.txt") as myfile:
for line in myfile:
flag=0
if ("SAM Account Type" in line):
for ch in line:
if (flag and ch!=' ' and ch!='\n'):
B+=ch
elif (ch == ':'):
flag+=1
S1 = myfile.read(10)
# print (ch)
elif (ch=='\n'):
flag =0
else:
pass
print (B)


This works like a charm only showing me "805306368"
But when I try to check for more variable other than "SAM Account Type" by using a list it fails to give the correct output.

For example the file below:


SAM Account Name : Ramachandran. S

SAM Account Type : 805306368

Description :

User Account Control : 544

When Created:09/21/2015 06:33:53

Lastlogontimestamp : 130966421275783509

When Changed : 01/07/2016 12:08:47

Account Expires : 922337203685477580

Last logoff : 00:00:00.0000000

Last logon : 130971364125825724


and this following code :

A = []
A.extend({"SAM Account Type",
"User Account Control",
"Last logon",
"Lastlogontimestamp",
"Last logoff",
"Account Expires"})
B = ""

with open("Sample.txt") as myfile:
for line in myfile:


for i in range(len(A)):
flag=0
if (str(A[i]) in line):
#if ("SAM Account Type" in line):
for ch in line:
if (flag and ch!=' ' and ch!='\n'):
B+=ch
elif (ch == ':'):
flag+=1
S1 = myfile.read(10)

elif (ch=='\n'):
flag =0
else:
pass
print (B)
B=""


Which Reads all the Characters after a ':' which Belong to an Entity in the list 'A' Stores them in 'B', and prints B for each line.

Gives The following:


'805306368'

'544'

'130966421275783509'

'922337203685477580'

'130971364125825724'


When it should also give for 'Last logoff' which is '00:00:00.0000000'
But it doesn't work. Any help would be highly appreciated.

Answer

As you are scanning for specific strings (ie those in A) I would create a list of each line in your file.

Split each line by ' : ' which seems to be the standard break between your key and your values in your txt file.

You now have a list that you can scan B and compare the first element of this list to the contents of A. We can print the second element (what appears after ' : ' for each match:

B=[]

with open("Sample.txt") as f:
  for line in f:
    B.append(line.split(' : ') 
for i in B:
  if i[0] in A:
    print i[1].strip()  #this removes the \n

Another 'fun' way to do this would be to create a dictionary

c={}
with open("Sample.txt") as f:
  for line in f:
   t=line.split(' : ')
   c.update({t[0]:t[1].split()})
for i in set(c.keys()) & set(A):  #gives set of matches between keys and A
  print c[1]

If you're into the whole brevity thing:

for i in open("Sample.txt").readlines():
  if i[:i.index(' : ')] in A:
    print i[i.index(' : ')+3:].split()[0]

Lastly:

print ''.join([i[i.index(' : ')+3:] for i in open("Sample.txt").readlines() if i[:i.index(' : ')] in A])