-1

I have multiple files with the first 8 lines being filled with different things, but I'd like to remove them across all files in multiple folders I have.

I've thought about using something like a pattern at first but I thought it would be a better idea to just give it the number of lines to delete since all the files have those first 8 lines.

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

But I gave up on this idea. Any way to remove a number of lines (at the beginning) of multiple fines at once?

Hi There
  • 167
  • 1
  • 5
  • 12
  • Does this answer your question? [How to read and delete first n lines from file in Python - Elegant Solution](https://stackoverflow.com/questions/42630639/how-to-read-and-delete-first-n-lines-from-file-in-python-elegant-solution) – Tomerikoo Aug 05 '21 at 10:23

4 Answers4

2

Try using itertools seems more elegant.

from itertools import islice
with open('SD') as f:
    for line in islice(f, 8, None):
        pass
Diya Li
  • 1,048
  • 9
  • 21
1

try this, where the list of your files' names should be in the files list variable

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:])
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Ghassen
  • 764
  • 6
  • 14
0

Another alternative combining @Ghassen and @James answers would be:

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")

read about os.replace

read about islice

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
-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)

Something like this maybe?

Cisco
  • 1
  • 1
  • No. You opened the file for writing. AND, when you loop on `lines_to_keep` you will simply add them at the end of the file – Tomerikoo Jun 22 '19 at 14:53
  • File is open in write, it will overwrite – Cisco Jun 22 '19 at 14:54
  • After executing `readlines()` your file pointer is at the end of the file. When performing the `write`s you simply add to the end of the file and not overwriting like you would think. And there is no such mode as `'rw'` what you wanted is `'r+'` – Tomerikoo Jun 22 '19 at 15:06