使用Python从一个文本文件复制到另一个文本文件

问题描述 投票:24回答:7

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

当前代码:

#!/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()
python text-files
7个回答
61
投票

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) 

6
投票

readlines()将整个输入文件读入列表,并不是一个好的执行者。只需遍历文件中的行。我在output.txt上使用'with',以便在完成后自动关闭。 'list1.txt'不需要这样做,因为当for循环结束时它将被关闭。

#!/usr/bin/env python
with open('output.txt', 'a') as f1:
    for line in open('list1.txt'):
        if 'tests/file/myword' in line:
            f1.write(line)

6
投票

这只是一个略微清理的方式。这并不比ATOzTOA的答案更好或更低,但没有理由做两个单独的陈述。

with open(path_1, 'a') as file_1, open(path_2, 'r') as file_2:
    for line in file_2:
        if 'tests/file/myword' in line:
            file_1.write(line)

1
投票
f=open('list1.txt')  
f1=open('output.txt','a')
for x in f.readlines():
    f1.write(x)
f.close()
f1.close()

这将100%尝试这一次


0
投票

安全和节省内存:

with open("out1.txt", "w") as fw, open("in.txt","r") as fr: 
    fw.writelines(l for l in fr if "tests/file/myword" in l)

它不会创建临时列表(readline[]会做什么,如果文件很大,这是一个非启动程序),所有都是使用生成器理解,并使用with块确保文件在退出时关闭。


0
投票

with open(“list1.txt”)as f:doIHaveToCopyTheLine = False'''在写模式下打开输出文件'''打开(“output.txt”,'w')为f1:'''逐行迭代'''对于f中的行:如果'tests / file / myword'在行中:doIHaveToCopyTheLine = True elif doIHaveToCopyTheLine:f1.write(line)

f1.close()f.close()


-1
投票
f = open('list1.txt')
f1 = open('output.txt', 'a')

# doIHaveToCopyTheLine=False

for line in f.readlines():
    if 'tests/file/myword' in line:
        f1.write(line)

f1.close()
f.close()

现在您的代码将起作用。试试这个。

© www.soinside.com 2019 - 2024. All rights reserved.