John
John

Reputation: 75

extracting lines from a text file

I am learning python and I am trying to solve some simple problems to get better. I have two files with the same length and I already extracted from the first file which lines I want to get from the second one. So now I have an array like [0, 1, 0, 0, 1, ...] for each line i want to read from the second file. What is the best way to copy only these lines in a third file? This is my code but i am getting errors in the writing line:

f = open('file.txt')
f2 = open('file2.txt', 'wb')
data = f.readlines()
for i in range(len(array)):
    if array[i]==1:
        f2.write(f[i])

Upvotes: 0

Views: 73

Answers (2)

icktoofay
icktoofay

Reputation: 129139

You'll probably want to zip your list and the file together:

for should_output, line in zip(array, f):
    if should_output:
        f2.write(line)

zip works on any number of iterables and groups corresponding elements together into an iterable of tuples, e.g.:

>>> zip([1, 2, 3], [4, 5, 6])
[(1, 4), (2, 5), (3, 6)]

You may also want to consider using the with statement to open your files, e.g.:

with open('input.txt', 'r') as input, open('output.txt', 'w') as output:
    for should_output, line in zip(array, input):
        if should_output:
            output.write(line)

The problem with your approach was that files aren't indexable (as you tried to do in f[i]). Fortunately, you read all the lines into the list data. If you want to stick with an approach more similar to your current one, you could simply replace f[i] with data[i].

Upvotes: 1

elyase
elyase

Reputation: 41003

You could use compress to select elements from an iterator:

from itertools import compress

l = [0, 1, 0, 1, 1, ...]     # your list
with open('second.txt') as src, open('third.txt', 'w') as dst:
    dst.writelines(compress(src, l))

Upvotes: 3

Related Questions