+ 1

How to delete a particular line of a file and then reorganise the file

i'm messing round with fie data manipulation and classes, but for a special deletion method i'm working on, how would i correctly re format the file after deleting one? the format goes: name; (name); Surname: (surname); pay: (pay) original code(it wont work on sololearn, but i've marked the area with the deletion behaviour: https://code.sololearn.com/cGHHyDSNcLVD

28th Oct 2017, 10:49 PM
X-1
X-1 - avatar
1 Odpowiedź
+ 2
You can load each line into a list and then loop over the list elements to check for the match to delete. The code below simulates this: # simulates file file = '''name: Tom; Surname: Hanks; pay: 20.00 name: Ben; Surname: Stiller; pay: 21.00 name: Jerry; Surname: McGuire; pay: 19.00 name: George; Surname: Clooney; pay: 20.00 name: Harry; Surname: Potter; pay: 18.00''' # make a list from the file spliting each line into an element file_list = file.split('\n') # create an empty list to store the modified file list new_file_list = [] # simulate deleting a line from the file by name for line in file_list: if line.startswith("Jerry", 6): continue new_file_list.append(line) # simulate writing each line from the new file list back to the file for line in new_file_list: print(line)
28th Oct 2017, 11:18 PM
ChaoticDawg
ChaoticDawg - avatar