0

I'm trying to loop through the command line arguments and open the files given. I try to read lines by using lines = file.readlines()and then use zip to combine items. But I don't know how to do it without knowing the list name. Here's my code:

import sys
import os
index = 1
while index < len(sys.argv):
    if os.path.exists(sys.argv[index]) == True:
        with open(sys.argv[index], 'r') as file:
            lines = file.readlines()
            #zip lines in files
        index = index + 1

And the contents of the file are:

file 1:

12

27

59

file 2:

21

72

95

Jesse
  • 23
  • 3

1 Answers1

0

in this approach you iterate through every argument, and append in to a list, at the end of each file it will apend to a new list, and you'll end up with a list of lists

import sys
import os
container = []
for document in sys.argv[1:]:
    if os.path.exists(document):
        aux = []
        with open(document, 'r') as file:
            for line in file:
                aux.append(line.replace('\n',''))
    container.append(aux)
print(*zip(*container))

Then you can just unpack the list and zip it, I manually replace the jump of line, do whatever you want with that. ;)

File 1 contains

7
1
3
5
6
3

File 2 contains

11
12
13
14
15

Input

python test.py test1.txt test2.txt

Output

('7', '11') ('1', '12') ('3', '13') ('5', '14') ('6', '15')

Edit

in this line "print(*zip(*container))", we are unpacking the container which is a list that has lists on it, when we zip it, as you may know when you zip something, a zip object is created, which is an iterable, in order to "unzip" it and to represent it as a set of tupples you use the * (starred expression), which unpacks it for example:

>>> a = zip([1,2,3,4,5], [5,4,3,2,1])
>>> print(a)
<zip object at 0x00000219ECE8C408>
>>> print(*a)
(1, 5) (2, 4) (3, 3) (4, 2) (5, 1) 
diegoiva
  • 454
  • 1
  • 8
  • 17