0

Pretty self explanatory. This is my text file:

C:\Windows\Users\Public\Documents\
C:\Program Files\Text Editor\

So, I have code which prompts the user to input the number of the line he wants to delete. But how do I delete the line which corresponds to the number?

EDIT :

To the person asking code:

# Viewing presets
if pathInput.lower() == 'view': 
    # Prints the lines in a numbered, vertical list.
    numLines = 1

    numbered = ''
    for i in lines:
        i = str(numLines) + '. ' + i
        numbered += i
        print (i)

        numLines += 1

    viewSelection = input('\n^ Avaiable Paths ^\nInput the preset\'s number you want to perform an action on.\n')

    for i in numbered:
        if viewSelection in i:
            viewAction = input('\nInput action for this preset.\nOptions: "Delete"')
            if viewAction.lower() == 'delete':

I simply want a way to delete a line by it's number in a file.

m1ksu
  • 109
  • 1
  • 2
  • 8
  • Instead of actually editing the original file, it's much easier to create a new file that has every line __except__ the one to be deleted, and then rename the file afterwards. – John Gordon Oct 31 '16 at 16:22
  • Possible duplicate of [How to get line count cheaply in Python?](http://stackoverflow.com/questions/845058/how-to-get-line-count-cheaply-in-python) – thesonyman101 Oct 31 '16 at 16:24
  • @Chris_Rands I haven't tried much. I updated the post with code. – m1ksu Oct 31 '16 at 16:34

1 Answers1

4

A simple approach would be to read the lines into a list, update the list, and write it back to the same file. Something like this:

with open("file.txt", "r+") as f:
    lines = f.readlines()
    del lines[linenum]  # use linenum - 1 if linenum starts from 1
    f.seek(0)
    f.truncate()
    f.writelines(lines)
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378