In python, you can open and read/write a file using..
f = open('your file - full path here', 'r')
You can also open it for writing using..
f = open('your file', 'w')
f.write("your text")
For your situation you might want to do this in a script (I am just giving you the overview)
1. Open the File
2. Read each line and concatenate the results to build your select query
using this after you open it..
for line in f:
print line
3. Print the concatenated results or store the result in another file using f.write()
*Note, you might want to write this as a python function so you can pass in the file to read from and the column name to use for your result query. I am not sure exactly how you are trying to use this.
I suggest you read this...
7. Input and Output — Python 2.7.8 documentation