繁体   English   中英

从文本文件中提取行

[英]extracting lines from a text file

我正在学习python,并且试图解决一些简单的问题以获得更好的结果。 我有两个长度相同的文件,我已经从第一个文件中提取了我想从第二个文件中提取的行。 所以现在我要从第二个文件中读取的每一行都有一个像[0,1,0,0,1,...]的数组。 将这些行仅复制到第三个文件的最佳方法是什么? 这是我的代码,但是在编写行时出现错误:

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

您可以使用compress从迭代器中选择元素:

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

您可能需要将列表和文件压缩在一起:

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

zip适用于任意数量的可迭代对象,并将相应的元素组合到一个可迭代的元组中,例如:

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

您可能还需要考虑使用with语句来打开文件,例如:

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)

您的方法的问题在于文件不可索引(就像您尝试在f[i] )。 幸运的是,您已将所有行读入列表data 如果您想采用与当前方法更相似的方法,则可以简单地将f[i]替换为data[i]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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