iOSecure iOSecure - 6 months ago 11
Python Question

How to go through a list of files

I'm trying to make a script that will run through a list of words one at a time and insert it in 3 areas on the script before starting over again. Then when it reaches the end of the list to stop.

wordlist = ['word1','word2','word3']


runs through
word1


csvinput = 'mainfile.csv'

reader = csv.reader(open(r'{0}'.format(csvinput)), delimiter=',')
filtered = filter(lambda p: 'word1' == p[6], reader)
csv.writer(open(r"word1\word1.csv",'w', newline = ''),delimiter=',').writerows(filtered)
time.sleep(0.1)


then starts over again but on
word2
etc.. until it reaches the end

Answer

Do you mean like this?

csvinput = 'mainfile.csv'
reader = csv.reader(open(r'{0}'.format(csvinput)), delimiter=',')

for word in wordlist:
    filtered = filter(lambda p: word == p[6], reader) 
    csv.writer(open("{}\{}.csv".format(word, word),'w', newline = ''),delimiter=',').writerows(filtered)
    time.sleep(0.1)

Some general documentation about looping through values: https://docs.python.org/3.4/tutorial/classes.html#iterators https://docs.python.org/3.4/tutorial/datastructures.html#looping-techniques

Comments