使用 Python 从一个文本文件复制到另一个文本文件 [英] Copying from one text file to another using Python

查看:136
本文介绍了使用 Python 从一个文本文件复制到另一个文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将某些文本行从一个文本文件复制到另一个文本文件.在我当前的脚本中,当我搜索一个字符串时,它会在之后复制所有内容,如何仅复制文本的特定部分?例如.仅在其中包含tests/file/myword"时复制行?

I would like to copy certain lines of text from one text file to another. In my current script when I search for a string it copies everything afterwards, how can I copy just a certain part of the text? E.g. only copy lines when it has "tests/file/myword" in it?

当前代码:

#!/usr/bin/env python
f = open('list1.txt')
f1 = open('output.txt', 'a')

doIHaveToCopyTheLine=False

for line in f.readlines():

    if 'tests/file/myword' in line:
        doIHaveToCopyTheLine=True

    if doIHaveToCopyTheLine:
        f1.write(line)

f1.close()
f.close()

推荐答案

oneliner:

open("out1.txt", "w").writelines([l for l in open("in.txt").readlines() if "tests/file/myword" in l])

推荐使用with:

with open("in.txt") as f:
    lines = f.readlines()
    lines = [l for l in lines if "ROW" in l]
    with open("out.txt", "w") as f1:
        f1.writelines(lines)

使用更少的内存:

with open("in.txt") as f:
    with open("out.txt", "w") as f1:
        for line in f:
            if "ROW" in line:
                f1.write(line) 

这篇关于使用 Python 从一个文本文件复制到另一个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆