Neemaximo
Neemaximo

Reputation: 20831

Reading from a file into a list and have each element go through the program

Sorry if the title is confusing. What I want to do is have a text file (keywords.txt) read and then split into a list. So basically lets say the file contained "iphone, keys, wallet, pen, folder", I would want the list to be [iphone, keys, wallet, pen, folder].

Is there any way to set one variable to work for each element. Say the variable is query. Is there anyway for query to be each of the elements so it can go through the program and work for each element. Below is the code I have, it obviously doesnt work but that is what I want to happen if possible.

The reason I want to do it for each is because eventually the script will write a new text file for each of the elements and name it based on what the element is and the only way I know how to do that is by having one variable.

data = [line.strip() for line in open('keywords.txt', 'r')]

try:
    query = sys.argv[1]
except IndexError:
    query = item in data 

Here is the rest of the code that I will be performing. It will take what is in the list that is created and create a new textfile and a csv file.

newFile = open("%s.txt" %query, 'w').write(txt.encode('utf8'))

with open("%s.txt" %query, 'rb') as input_file:
    reader = csv.reader(input_file, delimiter='\n', quoting = csv.QUOTE_NONE)

    with open("%s.csv" %query, 'wb') as output_file:
        writer = csv.writer(output_file)

        for row in reader:
            writer.writerow(row)

Upvotes: 0

Views: 85

Answers (2)

Inbar Rose
Inbar Rose

Reputation: 43497

def process_keywords_in_file(file_name):  
    with open(file_name) as f:
        for line in f:
            process(line.strip())

def process(keyword):
    #your code

if you want to write a new file with the name of the keyword:

with open('%s.txt' % keyword, 'w') as fw:
    fw.write('content')

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124748

Turn the query value taken from the command line into a list instead, then loop over the query list:

try:
    query = [sys.argv[1]]
except IndexError:
    query = data

for q in query:
    # do something with q

Upvotes: 2

Related Questions