Python Forum
delete line from a text file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
delete line from a text file
#1
i been trying for hours, no luck

the function ask the user what name he want to delete from the text file

def Delete_con():
    with open('phonebook1.txt', 'r+') as f:
        t = f.read()
        to_delete = input('What should we delete? : ').strip()
        f.seek(0)
        for line in t.split('\n'):
            if line != to_delete:
                f.write(line)
        f.truncate()
        return Menu()
Reply
#2
Perhaps replace line 8 with print(line, file=f)
Reply
#3
What errors do you get?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  File "<string>", line 19, in <module> error is related to what? Frankduc 9 12,541 Mar-09-2023, 07:22 AM
Last Post: LocklearSusan
  Getting last line of each line occurrence in a file tester_V 1 857 Jan-31-2023, 09:29 PM
Last Post: deanhystad
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,111 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,364 Sep-27-2022, 01:38 PM
Last Post: buran
  Graphic line plot with matplotlib, text file in pytho khadija 2 1,375 Aug-15-2022, 12:00 PM
Last Post: khadija
  Delete multiple lines from txt file Lky 6 2,281 Jul-10-2022, 12:09 PM
Last Post: jefsummers
  Delete empty text files [SOLVED] AlphaInc 5 1,546 Jul-09-2022, 02:15 PM
Last Post: DeaD_EyE
  Modify values in XML file by data from text file (without parsing) Paqqno 2 1,652 Apr-13-2022, 06:02 AM
Last Post: Paqqno
  Skipping line in text without Restarting Loop IdMineThat 4 1,475 Apr-05-2022, 04:23 AM
Last Post: deanhystad
  Print to a New Line when Appending File DaveG 0 1,217 Mar-30-2022, 04:14 AM
Last Post: DaveG

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020