JBond JBond - 5 months ago 11
Python Question

string (file1.txt) search from file2.txt

file1.txt
contains usernames, i.e.

tony
peter
john
...


file2.txt
contains user details, just one line for each user details, i.e.

alice 20160102 1101 abc
john 20120212 1110 zjc9
mary 20140405 0100 few3
peter 20140405 0001 io90
tango 19090114 0011 n4-8
tony 20150405 1001 ewdf
zoe 20000211 0111 jn09
...


I want to get a shortlist of user details from
file2.txt
by
file1.txt
user provided, i.e.

john 20120212 1110 zjc9
peter 20140405 0001 io90
tony 20150405 1001 ewdf


How to use python to do this?

Answer

You can use .split(' '), assuming that there will always be a space between the name and the other information in the file2.txt

Here's an example:

UserList = []

with open("file1.txt","r") as fuser:
        UserLine = fuser.readline()
        while UserLine!='':
            UserList.append(UserLine.split("\n")[0])    # Separate the user name from the new line command in the text file.
            UserLine = fuser.readline() 

InfoUserList = []   
InfoList = []

with open("file2.txt","r") as finfo:
        InfoLine = finfo.readline()
        while InfoLine!='':
            InfoList.append(InfoLine)
            line1 = InfoLine.split(' ')
            InfoUserList.append(line1[0])   # Take just the user name to compare it later
            InfoLine = finfo.readline()

for user in UserList:
    for i in range(len(InfoUserList)):
        if user == InfoUserList[i]:
            print InfoList[i]
Comments