r/programminghelp • • Feb 04 '20

Answered Read files line-by-line

I'm making a punnet-square generator and I need to read 2 files containing parent data line-by-line to see the first two characters of each line. I think I can go off from there by myself.

3 Upvotes

7 comments sorted by

2

u/amoliski Feb 04 '20
with open('filename', 'r') as f:
    for line in f.readlines():
             line.do.something.here

3

u/[deleted] Feb 04 '20

but how do you do it with 2 files at once?

2

u/amoliski Feb 04 '20

Say I gave you two books and asked you to hand me a piece of paper with the first letter of each chapter. How would you approach it manually?

3

u/[deleted] Feb 04 '20

You do it one at a time and use two different pieces of paper, then copy the 2 papers to one paper.

1

u/amoliski Feb 04 '20

Exactly, so what I would do is to make two empty lists, then go through all the files one at time and append the first letter to the associated list.

When you are done, you have two lists that you can then manipulate however you'd like. You also get the bonus of being able to see the length of both list so you can flag any issues if they have to be the same length.

Then I would do a

list_a = []
list_b = []

...read file a into list_a
...read file b into list_b

for i in range(len(list_a)):
    a = list_a[i]
    b = list_b[i]
    print(a, b)

And go from there.

You can also use zip to merge them together:

merged_list =  zip(list_a, list_b)
for a, b in merged_list:
     print(a, b)

Just note that zip will throw away data from the longer list if the two lists aren't the same length.

1

u/[deleted] Feb 05 '20

OK: I figured out how to do this, and then promptly got far enough ahead in development to not need to mess with it anymore.