简体   繁体   中英

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])

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))

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, eg:

>>> 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, eg:

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] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM