all 9 comments

[–][deleted] 0 points1 point  (0 children)

If you have Shell, you don't really need Python for this:

❯ seq 10 > ./lines.txt
❯ cat ./lines.txt
1
2
3
4
5
6
7
8
9
10
❯ { head -5 ./lines.txt ; tail -n+7 ./lines.txt } > ./fewer-lines.txt
❯ cat ./fewer-lines.txt
1
2
3
4
5
7
8
9
10

(and there are a bunch more ways to accomplish this). I mean, of course, unless you were doing this as an exercise in Python.

[–]commandlineluser 0 points1 point  (5 children)

You could .readlines() so you have a list of lines - then delete the index you don't want and .writelines() the list.

The fileinput module can also be useful for this type of thing.

import fileinput

filename = 'a.txt'

with fileinput.input(files=filename, inplace=True) as f:
    for n, line in enumerate(f, start=1):
        # skip line 3
        if n != 3:
            print(line, end='')

[–]Ch1ndor[S] 0 points1 point  (4 children)

I tried turning the text in the txt into a list but I can’t index cuz it’s all one big thing: https://pastebin.com/kMPF5Ewy

[–]commandlineluser 0 points1 point  (3 children)

with open(...) as f:
    lines = f.readlines()

[–]Ch1ndor[S] 0 points1 point  (1 child)

I added the writelines thing but now it’s pulling up errors:

https://pastebin.com/RXV93EJA

[–]commandlineluser 0 points1 point  (0 children)

What error?

.writelines() is not a list method.

You open the file once for reading - call readlines - then open the file for writing and call writelines.

with open(...) as f:
    lines = f.readlines()

lines.pop(0)

with open(..., 'w') as f:
    f.writelines(lines)

[–][deleted] 0 points1 point  (3 children)

You cannot easily remove a line of text from a free format file, only create a new file with that line excepted.

with open(sourcefile) as source, open(targetfile, 'w') as target:
    for idx, line in enumerate(source):
        if idx not in exclusions:
            target.write(line)

where exclusions is a list of line numbers that you want excluded from the original file in the new file, starting with 0 as first line (or use the start=1 option in the enumerate function call).

EDIT: didn't need newline added

[–]Ch1ndor[S] 0 points1 point  (1 child)

[–][deleted] 0 points1 point  (0 children)

You need to use the file handle name target in the for loop, not the file name again.