Python 2.7 Python:复制行,条件条件条件

Python 2.7 Python:复制行,条件条件条件,python-2.7,copy,Python 2.7,Copy,我一直在寻找以下Python解决方案,以便有选择地将行从一个txt文件复制到另一个txt文件。我可以复制整个文件,但只有几行我就出错了 我的代码: f = open(from_file, "r") g = open(to_file, "w") #copy = open(to_file, "w") # this instruction copies whole file rowcond2 = 'xxxx' # look for this string sequenc

我一直在寻找以下Python解决方案,以便有选择地将行从一个txt文件复制到另一个txt文件。我可以复制整个文件,但只有几行我就出错了

我的代码:

    f = open(from_file, "r")
    g = open(to_file, "w")
    #copy = open(to_file, "w") # this instruction copies whole file
    rowcond2 = 'xxxx' # look for this string sequence in every line

    for line in f:
        if rowcond2 in f:
            copy.write(line,"w") in g # write every corresponding line to  destination

    f.close()
    # copy.close() # code receive error to close destination
    g.close()
因此,没有rowcond2,我可以复制整个文件。但在这个条件下,并没有任何内容写入目标文件


感谢您的帮助。

为什么不将您的条件放入for循环中

for line in f:
    if condition:
        copy.write(line)

我已经能够解决这个案件,因此:


@卢卡斯·格拉夫:谢谢你详细的分步解释。

rowcond2到底应该做什么?或者您想要什么样的条件?“rowcond2”表示txt文件行中的字符串序列(例如“xxxx”)。这很有帮助!我的编码仍然在这两个文件之间混淆。根据您的建议,我已经更正了代码(请参阅我的第一个条目)。