如何在循环中附加的文件中打印特定行?

时间:2016-04-17 11:36:30

标签: python python-2.7 python-3.x with-statement

from itertools import zip_longest 
f = open("all_info.txt", "a")
with open("all_info.txt") as f, open ("over_speeding.txt") as f1, open("fine.txt") as fine, open("all details.txt", "a") as everything:
     for fline, fineline in zip_longest (f, fine, fillvalue=""): 
          everything.write (fineline.strip() + "   ---   " + fline.strip() + "\n")      


          a = open("all details.txt", "r")
          for line in everything:#the problem
               everything.strip()
               if line in f1:
                    with ("fine1.txt", "a") as fine1:
                         fine1.write(line)

这只是我整个代码的一部分。我的整个代码需要车辆登记号,然后检查它是否是标准的。然后输入行驶1英里的时间,用于计算速度。

如果速度大于70英里/小时,登记号码和车辆行驶的速度将转到文件over_speeding.txt。然后其他条件确定详细信息去哪个文件(但这并不重要)。

我向你展示的代码将打开4个文件,其中fine.txt文件已经设置,over_speeding.txt文件从我的整个代码中获取数据。 all_info.txt文件将存储我整个代码的所有输入,然后使用zip_lingest模块将all_info.txt文件附加到fine.txt到all_details.txt文件。

我想要只选择超出的所有details.txt中的行,然后将其保存到fine1.txt

e.g。 fine.txt

11111
22222
33333
44444

all_info.txt

xxxxxxxx
dddddddd
aaaaaaaa
cccccccc

all_details.txt

11111 --- xxxxxxxx
22222 --- dddddddd
33333 --- aaaaaaaa
44444 --- cccccccc

如果

xxxxxxx 

aaaaaaa 

来自文件over_speeding.txt,然后是所有details.txt文件:

11111 --- xxxxxxxx
33333 --- aaaaaaaa

应保存到fine1.txt文件

1 个答案:

答案 0 :(得分:1)

我在理解您的代码时遇到了问题(当有人试图读取您的代码时,变量的名称确实没有用,至少对我而言),但我已经尝试按照您的预期重写它:

from itertools import zip_longest
#EDIT why open all_info.txt twice?
#f = open("all_info.txt", "a")
with open("all_info.txt", "a") as f,\
    open("over_speeding.txt") as f1,\
    open("fine.txt") as fine,\
    open("all details.txt", "a") as everything,\
    open("fine1.txt", "a") as fine1: # moved opening fine1 here

    for fline, fineline in zip_longest(f, fine, fillvalue=""):
        #EDIT
        line_to_write = fineline.strip() + "   ---   " + fline.strip() # so we don't need to write it twice
        everything.write(line_to_write + "\n") # write to file with newline
        if line_to_write in f1: # compare the line with values in over_speeding
            fine1.write(line_to_write)

因为它只是脚本的一部分而我没有所有数据我无法测试它。您的方法:将所有行写入所有内容,然后分别检查所有行。我的方法:获取行,写入并在同一循环中检查它。如果我理解你的代码,它应该做同样的事情。请询问或指出任何错误/误解。