+ 1
How to delete a user specified line from a text file in python? (The file contains different lines with dictionary)
There is a text file my_file.txt which contains several rows of dictionary items {big: small} {high: low} {thin: thick} How to delete any item from this file that user chooses?
18 Answers
+ 3
To delete a specified line from a text file can be done for example in this way:
https://code.sololearn.com/c6ej3sFhb0aj/?ref=app
But for a very big number of data records it would be recomended to use a database for the application.
+ 2
I see . Thats one way to do it glad you figured it out
+ 1
with open('scratch_4.txt', 'r+') as file:
with open('new.txt', 'w') as new_file:
for line in file:
line = line.strip()
if remove_item in line:
continue:
new_file.write(line)
0
Title asks how to delete a line from a text file but in Description it asks how to delete any item - presumably was referring to the dictionary item - not the line.
Please clarify or edit the post to confirm which one it is, even better ...
0
can the user chooseJust 1 or multiple, if the user pick big can he also pick small or is big the key and small the value which means big gets deleted as a whole?
0
Only one item can be chosen at a time. Input will be key only. Using key, I map value and identify the item.
0
Did you try to do it ? Neethu Nath
0
I tried to use line.strip() but I cannot check if a dictionary in line
0
Can you show ?
0
It is giving error
TypeError: 'in <string>' requires string as left operand, not dict
0
Youre pretty close remove the + from read mode, for line in file.readlines() remove reset of line below and just print line
0
then you can continue from there repost your code
0
Oh forgot it might overwite file so it may not print anything
0
https://pastebin.com/Cq9d3HRY pw: booker
Change text_file to w.e your file is
0
I changed the logic completely and solved this
0
Awsome ! :D can i see your newly logic ?
0
I used single dictionary to add all inputs instead of each item in a row
0
Thank you for trying to help me