ran1n
ran1n

Reputation: 157

Zip two file contents having related timestamp column to create a list in python

I have two files containing timestamp column with 1000+ rows. Row in file f1 is related to the row in file f2. I wanted a Python script to do [f1 nth row,f2 nth row] for all corresponding rows in the best way possible. Thanks!

f1:  
05:43:44  
05:59:32

f2:  
05:43:51  
05:59:39

e.g. [05:43:44,05:43:51], [05:59:32,05:59:39] ....

Upvotes: 0

Views: 124

Answers (3)

David542
David542

Reputation: 110219

You can do something like the following:

f1_as_list = open(f1).readlines() # get each line as a list element
f2_as_list = open(f2).readlines()
zipped_files = zip(f1_as_list, f2_as_list) # zip the two lists together

Upvotes: 1

Drew Faubion
Drew Faubion

Reputation: 3

Something like this is probably the most intuitive approach.

#!/usr/bin/python3
with open("f1.txt") as f1:
  with open("f2.txt") as f2:
    for row1 in f1:
      for row2 in f2:
        print("%s %s" % (row1.strip(), row2.strip()))

Some might prefer a list comprehension, but non-pythonistas may not consider it intuitive.

with open("f1.txt") as f1:
  with open("f2.txt") as f2:
    print("\n".join([
      "%s %s" % (row1.strip(), row2.strip())
      for row1 in f1
      for row2 in f2
    ]))

Upvotes: 0

You may use zip() function. https://docs.python.org/3/library/functions.html#zip

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]

Upvotes: 2

Related Questions