从多个文件中删除多行

时间:2019-06-22 14:38:21

标签: python

我有多个文件,前8行充满了不同的内容,但我想在我拥有的多个文件夹中的所有文件中删除它们。

我曾考虑过首先使用类似模式的内容,但我认为最好给它提供要删除的行数,因为所有文件都具有前8行。

f = open('SD')
lines = f.readlines()
f.close()

result = []
bool_remover = False
for line in lines:
    if line == "Greg*" : bool_remover = True
    if not bool_remover : result.append(line)
    if line == "***" : bool_remover = False

但是我放弃了这个想法。有什么方法可以一次(多次删除)多个罚款行?

4 个答案:

答案 0 :(得分:2)

尝试使用itertools似乎更优雅。

from itertools import islice
with open('SD') as f:
    for line in islice(f, 8, None):
        pass

答案 1 :(得分:1)

尝试此操作,文件名列表应在files列表变量中

files = ["file1.txt","file2.txt"]
for file in files:
    with open('file', 'r') as fin:
        data = fin.read().splitlines(True)
    with open('file', 'w') as fout:
        fout.writelines(data[8:])

答案 2 :(得分:0)

结合@Ghassen和@James答案的另一种选择是:

from itertools import islice
import os

with open('file1.txt') as in_f, open("tmp.txt", 'w') as out_f:
    for line in islice(in_f, 8, None):
        out_f.write(line)

os.replace("tmp.txt", "file1.txt")

了解os.replace

了解islice

答案 3 :(得分:-2)

Files = [f1,f2,...] # f1,... are the filepaths
for filepath in Files:

    with open(filepath, "rw") as f:

        lines_to_keep = f.readlines()[8:]

        for line in lines_to_keep:

            f.write(line)

也许是这样?