Peter S
Peter S

Reputation: 575

iterate over list of tuple pairs (python 3.x)

i sorted files by their date in their `filename in a list of tuples holding each matching pair.

print (matching_files)

output:

[('sample_20140809.csv', 'data_20140809.csv'),('sample_20140806.csv', 'data_20140806.csv'), ('sample_20140801.csv', 'data_20140801.csv')

Question: How can I iterate over each tuple pair?

I want to open sample_20140809.csv data_20140809.csv do something to those files, write a new file and than loop to the next pair and so on until there are no more pairs in the folder ....

something like: for a,b in matching_pairs: but what do I need to do If I just want to use a pair each loop ...

Upvotes: 1

Views: 1456

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

You are close, after loop you can just open the files and create a writer object of them using csv module :

import csv
for a,b in matching_pairs:
    with open(a,'w') as file_obj1,open(b,'w') as file_obj2:
        spam_writer1=csv.writer(file_obj1,delimiter=',')
        spam_writer2=csv.writer(file_obj2,delimiter=',')
        # do stuff

Note that you can pass your own delimiters to writer object here for example I have passed the comma as delimiter.

Read more about csv module https://docs.python.org/3/library/csv.html

Upvotes: 1

Related Questions